utils.c (1019B)
1 #include "utils.h" 2 3 /* 4 * Convert a byte string to an integer. 5 */ 6 uint64_t to_int(const uint8_t *x, const size_t n) { 7 assert(n <= 8); // max 64 bits 8 9 uint64_t res = 0; 10 size_t i; 11 for (i = 0; i < n; i++) { 12 res = (res << 8) + (uint64_t)x[i]; 13 } 14 15 return res; 16 } 17 18 /* 19 * Convert an integer to bytes. 20 */ 21 void to_bytes(uint8_t *bytes, const size_t len, uint64_t in) { 22 assert(len <= 8); 23 size_t i; 24 for (i = 0; i < len; i++) { 25 bytes[len - 1 - i] = (uint8_t)(in & 0xff); 26 in >>= 8; 27 } 28 } 29 30 /* 31 * Compute the base 2^b representation of X. 32 */ 33 void base_2b(uint64_t *out, const uint8_t *x, const size_t xsz, 34 const uint64_t b, const size_t out_len) { 35 uint64_t in = 0; 36 uint64_t bits = 0; 37 uint64_t total = 0; 38 39 assert(b < 64); 40 uint64_t b_mask = (1 << b) - 1; 41 42 size_t i; 43 for (i = 0; i < out_len; i++) { 44 while (bits < b) { 45 total = (total << 8) + (uint64_t)x[in]; // overflow ok 46 in++; 47 bits += 8; 48 } 49 50 bits -= b; 51 out[i] = (total >> bits) & b_mask; 52 } 53 }