1 #include <bitfield/bitfield.h>
4 * Find the ending bit of a bitfield within the final byte.
6 * Returns: a bit position from 0 to 7.
8 int findEndBit(int startBit, int numBits) {
9 int endBit = (startBit + numBits) % 8;
10 return endBit == 0 ? 8 : endBit;
13 uint64_t bitmask(int numBits) {
14 return (((uint64_t)0x1) << numBits) - 1;
17 int startingByte(int startBit) {
21 int endingByte(int startBit, int numBits) {
22 return (startBit + numBits - 1) / 8;
25 uint64_t getBitField(uint64_t data, int startBit, int numBits, bool bigEndian) {
26 int startByte = startingByte(startBit);
27 int endByte = endingByte(startBit, numBits);
30 data = __builtin_bswap64(data);
32 uint8_t* bytes = (uint8_t*)&data;
33 uint64_t ret = bytes[startByte];
34 if(startByte != endByte) {
35 // The lowest byte address contains the most significant bit.
37 for(i = startByte + 1; i <= endByte; i++) {
43 ret >>= 8 - findEndBit(startBit, numBits);
44 return ret & bitmask(numBits);
48 * TODO it would be nice to have a warning if you call with this a value that
49 * won't fit in the number of bits you've specified it should use.
51 void setBitField(uint64_t* data, uint64_t value, int startBit, int numBits) {
52 int shiftDistance = 64 - startBit - numBits;
53 value <<= shiftDistance;
54 *data &= ~(bitmask(numBits) << shiftDistance);
58 uint8_t nthByte(uint64_t source, int byteNum) {
59 return (source >> (64 - ((byteNum + 1) * 8))) & 0xFF;