1 #include <bitfield/bitfield.h>
2 #include <bitfield/8byte.h>
7 uint64_t bitmask(const uint8_t numBits) {
8 return (((uint64_t)0x1) << numBits) - 1;
11 static uint16_t bitsToBytes(uint32_t bits) {
12 uint8_t byte_count = bits / CHAR_BIT;
13 if(bits % CHAR_BIT != 0) {
19 uint64_t getBitField(uint64_t data, const uint16_t startBit,
20 const uint16_t numBits, bool bigEndian) {
21 uint8_t result[8] = {0};
23 data = __builtin_bswap64(data);
25 copyBitsRightAligned((const uint8_t*)&data, sizeof(data), startBit, numBits,
26 result, sizeof(result));
27 uint64_t int_result = 0;
30 // we need to swap the byte order of the array to get it into a
31 // uint64_t, but it's been right aligned so we have to be more careful
32 for(int i = 0; i < bitsToBytes(numBits); i++) {
33 int_result |= result[bitsToBytes(numBits) - i - 1] << (CHAR_BIT * i);
36 int_result = *(uint64_t*)result;
42 * TODO it would be nice to have a warning if you call with this a value that
43 * won't fit in the number of bits you've specified it should use.
45 void setBitField(uint64_t* data, uint64_t value, const uint16_t startPos,
46 const uint16_t numBits) {
47 int shiftDistance = 64 - startPos - numBits;
48 value <<= shiftDistance;
49 *data &= ~(bitmask(numBits) << shiftDistance);
53 uint8_t nthByte(const uint64_t source, const uint16_t byteNum) {
54 return (source >> (64 - ((byteNum + 1) * CHAR_BIT))) & 0xFF;