Update README.md
[oweals/nmrpflash.git] / util.c
1 /**
2  * nmrpflash - Netgear Unbrick Utility
3  * Copyright (C) 2016 Joseph Lehner <joseph.c.lehner@gmail.com>
4  *
5  * nmrpflash is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * nmrpflash is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with nmrpflash.  If not, see <http://www.gnu.org/licenses/>.
17  *
18  */
19
20 #include <stdio.h>
21 #include <errno.h>
22 #include <time.h>
23 #include <math.h>
24 #include "nmrpd.h"
25
26 #ifdef NMRPFLASH_OSX
27 #include <mach/mach_time.h>
28 #endif
29
30 volatile sig_atomic_t g_interrupted = 0;
31
32 time_t time_monotonic()
33 {
34 #ifndef NMRPFLASH_WINDOWS
35 #ifndef NMRPFLASH_OSX
36         struct timespec ts;
37         clock_gettime(CLOCK_MONOTONIC, &ts);
38         return ts.tv_sec;
39 #else
40         static double factor = 0.0;
41         mach_timebase_info_data_t timebase;
42         if (factor == 0.0) {
43                 mach_timebase_info(&timebase);
44                 factor = (double)timebase.numer / timebase.denom;
45         }
46
47         return round(mach_absolute_time() * factor / 1e9);
48 #endif
49 #else
50         return round(GetTickCount() / 1000.0);
51 #endif
52 }
53
54 char *lltostr(long long ll, int base)
55 {
56         static char buf[32];
57         snprintf(buf, sizeof(buf) - 1, (base == 16 ? "%llx" : (base == 8 ? "%llo" : "%lld")), ll);
58         return buf;
59 }
60
61 uint32_t bitcount(uint32_t n)
62 {
63         uint32_t c;
64         for (c = 0; n; ++c) {
65                 n &= n - 1;
66         }
67         return c;
68 }
69
70 uint32_t netmask(uint32_t count)
71 {
72         return htonl(count <= 32 ? 0xffffffff << (32 - count) : 0);
73 }
74
75 void xperror(const char *msg)
76 {
77         if (errno != EINTR) {
78                 perror(msg);
79         } else {
80                 printf("\n");
81         }
82 }