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