1 #include <bitfield/bitfield.h>
7 uint64_t bitmask(const uint8_t bit_count) {
8 return (((uint64_t)0x1) << bit_count) - 1;
11 uint8_t get_nibble(const uint8_t source[], const uint8_t source_length,
12 const uint8_t nibble_index) {
13 uint8_t byte_index = nibble_index / 2;
14 uint8_t result = get_byte(source, source_length, byte_index);
15 if(nibble_index % 2 == 0) {
16 result >>= NIBBLE_SIZE;
18 result &= bitmask(NIBBLE_SIZE);
22 uint8_t get_byte(const uint8_t source[], const uint8_t source_length,
23 const uint8_t byte_index) {
24 if(byte_index < source_length) {
25 return source[byte_index];
30 uint64_t get_bitfield(const uint8_t source[], const uint8_t source_length,
31 const uint16_t offset, const uint16_t 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 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);
44 return combined.whole;
47 bool set_nibble(const uint16_t nibble_index, const uint8_t value,
48 uint8_t* destination, const uint16_t destination_length) {
49 return copy_bits(&value, CHAR_BIT, NIBBLE_SIZE, NIBBLE_SIZE, destination,
50 destination_length, nibble_index * NIBBLE_SIZE);
53 bool set_bitfield(const uint64_t value, const uint16_t offset,
54 const uint16_t bit_count, uint8_t destination[],
55 uint16_t destination_length) {
56 if(value > bitmask(bit_count)) {
60 ArrayOrBytes combined = {
64 if(BYTE_ORDER == LITTLE_ENDIAN) {
65 combined.whole = __builtin_bswap64(combined.whole);
68 return copy_bits(combined.bytes, sizeof(combined.bytes),
69 sizeof(combined.bytes) * CHAR_BIT - bit_count, bit_count,
70 destination, destination_length, offset);