summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJakob Kaivo <jkk@ung.org>2019-08-08 09:29:16 -0400
committerJakob Kaivo <jkk@ung.org>2019-08-08 09:29:16 -0400
commite4685300ab39ddd837f89f210c2ae270bea7465b (patch)
treebd4375aada55c9a5604a1308faa402d413c97882
parent9c9727a13fb8e23a26bd409be3796bd571bd8ead (diff)
add conversion function binstr()
-rw-r--r--binary.h18
1 files changed, 16 insertions, 2 deletions
diff --git a/binary.h b/binary.h
index ba19165..9046396 100644
--- a/binary.h
+++ b/binary.h
@@ -2,8 +2,10 @@
#include <string.h>
#include <stdint.h>
+#define BIT_UINTMAXBITS (sizeof(uintmax_t) * CHAR_BIT)
+
#define BIN_BIT(_s, _b) (\
- sizeof(_s) > (_b+1) || (_b+1) > sizeof(uintmax_t) * CHAR_BIT ? \
+ sizeof(_s) > (_b + 1) || (_b + 1) > BIT_UINTMAXBITS ? \
(uintmax_t)0 : \
_s[sizeof(_s)-(_b+1)] == '0' ? \
(uintmax_t)0 : \
@@ -33,8 +35,20 @@
static uintmax_t binfromstr(const char *s)
{
- char array[sizeof(uintmax_t) * CHAR_BIT + 1];
+ char array[BIT_UINTMAXBITS + 1];
memset(array, '0', sizeof(array));
strcpy(array + (sizeof(array) - strlen(s)) - 1, s);
return BIN_FROM_ARRAY(array);
}
+
+static char *binstr(size_t n, char s[n], uintmax_t b)
+{
+ memset(s, '0', n);
+ s[n - 1] = '\0';
+ for (size_t i = 0; i < n && i < BIT_UINTMAXBITS; i++) {
+ if (b & (1 << i)) {
+ s[n - (i + 1)] = '1';
+ }
+ }
+ return s;
+}