Check subnet mask's sanity
[oweals/nmrpflash.git] / util.c
1 #include <stdio.h>
2 #include <time.h>
3 #include <math.h>
4 #include "nmrpd.h"
5
6 #ifdef NMRPFLASH_OSX
7 #include <mach/mach_time.h>
8 #endif
9
10 time_t time_monotonic()
11 {
12 #ifndef NMRPFLASH_WINDOWS
13 #ifndef NMRPFLASH_OSX
14         struct timespec ts;
15         clock_gettime(CLOCK_MONOTONIC, &ts);
16         return ts.tv_sec;
17 #else
18         static double factor = 0.0;
19         mach_timebase_info_data_t timebase;
20         if (factor == 0.0) {
21                 mach_timebase_info(&timebase);
22                 factor = (double)timebase.numer / timebase.denom;
23         }
24
25         return round(mach_absolute_time() * factor / 1e9);
26 #endif
27 #else
28         return round(GetTickCount() / 1000.0);
29 #endif
30 }
31
32 char *lltostr(long long ll, int base)
33 {
34         static char buf[32];
35         snprintf(buf, sizeof(buf) - 1, (base == 16 ? "%llx" : (base == 8 ? "%llo" : "%lld")), ll);
36         return buf;
37 }
38
39 uint32_t bitcount(uint32_t n)
40 {
41         uint32_t c;
42         for (c = 0; n; ++c) {
43                 n &= n - 1;
44         }
45         return c;
46 }
47
48 uint32_t netmask(uint32_t count)
49 {
50         return htonl(count <= 32 ? 0xffffffff << (32 - count) : 0);
51 }