1 #include <bitfield/bitfield.h>
7 uint64_t bitmask(const unsigned int bit_count) {
8 return (((uint64_t)0x1) << bit_count) - 1;
11 unsigned int get_nibble(const uint8_t source[], const unsigned int source_length,
12 const unsigned int nibble_index) {
13 unsigned int byte_index = nibble_index / 2;
14 unsigned int result = get_byte(source, source_length, byte_index);
15 if(nibble_index % 2 == 0) {
16 result >>= NIBBLE_SIZE;
18 result &= bitmask(NIBBLE_SIZE);
22 unsigned int get_byte(const uint8_t source[], const unsigned int source_length,
23 const unsigned int byte_index) {
24 if(byte_index < source_length) {
25 return source[byte_index];
30 uint64_t get_bitfield(const uint8_t source[], const unsigned int source_length,
31 const unsigned int offset, const unsigned int bit_count) {
32 if(bit_count > 64 || bit_count < 1) {
33 // TODO error reporting?
37 ArrayOrBytes combined;
38 memset(combined.bytes, 0, sizeof(combined.bytes));
39 if(copy_bits_right_aligned(source, source_length, offset, bit_count,
40 combined.bytes, sizeof(combined.bytes))) {
41 if(BYTE_ORDER == LITTLE_ENDIAN) {
42 combined.whole = __builtin_bswap64(combined.whole);
45 // debug("couldn't copy enough bits from source")
47 return combined.whole;
50 bool set_nibble(const unsigned int nibble_index, const unsigned int value,
51 uint8_t* destination, const unsigned int destination_length) {
52 return copy_bits(&value, CHAR_BIT, NIBBLE_SIZE, NIBBLE_SIZE, destination,
53 destination_length, nibble_index * NIBBLE_SIZE);
56 bool set_bitfield(const uint64_t value, const unsigned int offset,
57 const unsigned int bit_count, uint8_t destination[],
58 unsigned int destination_length) {
59 if(value > bitmask(bit_count)) {
63 ArrayOrBytes combined = {
67 if(BYTE_ORDER == LITTLE_ENDIAN) {
68 combined.whole = __builtin_bswap64(combined.whole);
71 return copy_bits(combined.bytes, sizeof(combined.bytes),
72 sizeof(combined.bytes) * CHAR_BIT - bit_count, bit_count,
73 destination, destination_length, offset);