Rename library, it's not really about CAN.
[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 #define EIGHTBYTE_BIT (8 * sizeof(uint64_t))
8
9 uint64_t bitmask(const uint8_t bit_count) {
10     return (((uint64_t)0x1) << bit_count) - 1;
11 }
12
13 static uint16_t bits_to_bytes(uint32_t bits) {
14     uint8_t byte_count = bits / CHAR_BIT;
15     if(bits % CHAR_BIT != 0) {
16         ++byte_count;
17     }
18     return byte_count;
19 }
20
21 uint8_t eightbyte_get_nibble(const uint64_t source, const uint8_t nibble_index,
22         const bool big_endian) {
23     return get_bit_field(source, NIBBLE_SIZE * nibble_index, NIBBLE_SIZE,
24             big_endian);
25 }
26
27 uint8_t eightbyte_get_byte(const uint64_t source, const uint8_t byte_index,
28         const bool big_endian) {
29     // TODO we're not handling swapped endianness - we could use get_bit_field
30     // but this might be more efficient
31     return (source >> (EIGHTBYTE_BIT - ((byte_index + 1) * CHAR_BIT))) & 0xFF;
32 }
33
34 uint64_t get_bit_field(uint64_t source, const uint16_t offset,
35         const uint16_t bit_count, const bool big_endian) {
36     int startByte = offset / CHAR_BIT;
37     int endByte = (offset + bit_count - 1) / CHAR_BIT;
38
39     if(!big_endian) {
40         source = __builtin_bswap64(source);
41     }
42
43     uint8_t* bytes = (uint8_t*)&source;
44     uint64_t ret = bytes[startByte];
45     if(startByte != endByte) {
46         // The lowest byte address contains the most significant bit.
47         int i;
48         for(i = startByte + 1; i <= endByte; i++) {
49             ret = ret << 8;
50             ret = ret | bytes[i];
51         }
52     }
53
54     ret >>= 8 - find_end_bit(offset + bit_count);
55     return ret & bitmask(bit_count);
56 }
57
58 bool set_bit_field(uint64_t* destination, uint64_t value, const uint16_t offset,
59         const uint16_t bit_count) {
60     if(value > bitmask(bit_count)) {
61         return false;
62     }
63
64     int shiftDistance = EIGHTBYTE_BIT - offset - bit_count;
65     value <<= shiftDistance;
66     *destination &= ~(bitmask(bit_count) << shiftDistance);
67     *destination |= value;
68     return true;
69 }