1 #include <bitfield/bitfield.h>
6 #define NIBBLE_SIZE (CHAR_BIT / 2)
8 uint64_t bitmask(const uint8_t numBits) {
9 return (((uint64_t)0x1) << numBits) - 1;
12 static uint16_t bitsToBytes(uint32_t bits) {
13 uint8_t byte_count = bits / CHAR_BIT;
14 if(bits % CHAR_BIT != 0) {
20 uint64_t getBitField(uint64_t data, const uint16_t startBit,
21 const uint16_t numBits, bool bigEndian) {
22 uint8_t result[8] = {0};
24 data = __builtin_bswap64(data);
26 copyBitsRightAligned((const uint8_t*)&data, sizeof(data), startBit, numBits,
27 result, sizeof(result));
28 uint64_t int_result = 0;
31 // we need to swap the byte order of the array to get it into a
32 // uint64_t, but it's been right aligned so we have to be more careful
33 for(int i = 0; i < bitsToBytes(numBits); i++) {
34 int_result |= result[bitsToBytes(numBits) - i - 1] << (CHAR_BIT * i);
37 int_result = *(uint64_t*)result;
43 * TODO it would be nice to have a warning if you call with this a value that
44 * won't fit in the number of bits you've specified it should use.
46 void setBitField(uint64_t* data, uint64_t value, const uint16_t startPos,
47 const uint16_t numBits) {
48 int shiftDistance = 64 - startPos - numBits;
49 value <<= shiftDistance;
50 *data &= ~(bitmask(numBits) << shiftDistance);
54 uint8_t nthByte(const uint64_t source, const uint16_t byteNum) {
55 return (source >> (64 - ((byteNum + 1) * CHAR_BIT))) & 0xFF;
58 uint8_t getNibble(const uint8_t nibble_index, const uint8_t data[],
59 const uint8_t length) {
60 uint8_t byte_index = nibble_index / 2;
62 if(byte_index < length) {
63 result = data[byte_index];
64 if(nibble_index % 2 == 0) {
65 result >>= NIBBLE_SIZE;
68 result &= bitmask(NIBBLE_SIZE);
72 uint8_t getByte(const uint8_t byte_index, const uint8_t data[],
73 const uint8_t length) {
74 if(byte_index < length) {
75 return data[byte_index];