Split up 8 byte wrappers from generic bit array functions.
[apps/agl-service-can-low-level.git] / src / bitfield / 8byte.c
1 #include <bitfield/bitfield.h>
2 #include <bitfield/8byte.h>
3 #include <stddef.h>
4 #include <limits.h>
5 #include <string.h>
6
7 uint64_t bitmask(const uint8_t numBits) {
8     return (((uint64_t)0x1) << numBits) - 1;
9 }
10
11 static uint16_t bitsToBytes(uint32_t bits) {
12     uint8_t byte_count = bits / CHAR_BIT;
13     if(bits % CHAR_BIT != 0) {
14         ++byte_count;
15     }
16     return byte_count;
17 }
18
19 uint64_t getBitField(uint64_t data, const uint16_t startBit,
20         const uint16_t numBits, bool bigEndian) {
21     uint8_t result[8] = {0};
22     if(!bigEndian) {
23         data = __builtin_bswap64(data);
24     }
25     copyBitsRightAligned((const uint8_t*)&data, sizeof(data), startBit, numBits,
26             result, sizeof(result));
27     uint64_t int_result = 0;
28
29     if(!bigEndian) {
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);
34         }
35     } else {
36         int_result = *(uint64_t*)result;
37     }
38     return int_result;
39 }
40
41 /**
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.
44  */
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);
50     *data |= value;
51 }
52
53 uint8_t nthByte(const uint64_t source, const uint16_t byteNum) {
54     return (source >> (64 - ((byteNum + 1) * CHAR_BIT))) & 0xFF;
55 }
56