d383db04a047dd79158e80f838e0c62e175ee018
[apps/agl-service-can-low-level.git] / src / bitfield / bitfield.c
1 #include <bitfield/bitfield.h>
2
3 /**
4  * Find the ending bit of a bitfield within the final byte.
5  *
6  * Returns: a bit position from 0 to 7.
7  */
8 int findEndBit(int startBit, int numBits) {
9     int endBit = (startBit + numBits) % 8;
10     return endBit == 0 ? 8 : endBit;
11 }
12
13 uint64_t bitmask(int numBits) {
14     return (((uint64_t)0x1) << numBits) - 1;
15 }
16
17 int startingByte(int startBit) {
18     return startBit / 8;
19 }
20
21 int endingByte(int startBit, int numBits) {
22     return (startBit + numBits - 1) / 8;
23 }
24
25 uint64_t getBitField(uint64_t data, int startBit, int numBits, bool bigEndian) {
26     int startByte = startingByte(startBit);
27     int endByte = endingByte(startBit, numBits);
28
29     if(!bigEndian) {
30         data = __builtin_bswap64(data);
31     }
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.
36         int i;
37         for(i = startByte + 1; i <= endByte; i++) {
38             ret = ret << 8;
39             ret = ret | bytes[i];
40         }
41     }
42
43     ret >>= 8 - findEndBit(startBit, numBits);
44     return ret & bitmask(numBits);
45 }
46
47 /**
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.
50  */
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);
55     *data |= value;
56 }
57
58 uint8_t nthByte(uint64_t source, int byteNum) {
59     return (source >> (64 - ((byteNum + 1) * 8))) & 0xFF;
60 }