Checkpoint commit renaming some functions for clarity.
[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 uint8_t eightbyte_get_nibble(const uint64_t source, const uint8_t nibble_index,
10         const bool data_is_big_endian) {
11     return eightbyte_get_bit_field(source, NIBBLE_SIZE * nibble_index, NIBBLE_SIZE,
12             data_is_big_endian);
13 }
14
15 uint8_t eightbyte_get_byte(uint64_t source, const uint8_t byte_index,
16         const bool data_is_big_endian) {
17     if(data_is_big_endian) {
18         source = __builtin_bswap64(source);
19     }
20     return (source >> (EIGHTBYTE_BIT - ((byte_index + 1) * CHAR_BIT))) & 0xFF;
21 }
22
23 uint64_t eightbyte_get_bit_field(uint64_t source, const uint16_t offset,
24         const uint16_t bit_count, const bool data_is_big_endian) {
25     int startByte = offset / CHAR_BIT;
26     int endByte = (offset + bit_count - 1) / CHAR_BIT;
27
28     if(!data_is_big_endian) {
29         source = __builtin_bswap64(source);
30     }
31
32     uint8_t* bytes = (uint8_t*)&source;
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 - find_end_bit(offset + bit_count);
44     return ret & bitmask(bit_count);
45 }
46
47 bool set_bit_field(uint64_t* destination, uint64_t value, const uint16_t offset,
48         const uint16_t bit_count) {
49     if(value > bitmask(bit_count)) {
50         return false;
51     }
52
53     int shiftDistance = EIGHTBYTE_BIT - offset - bit_count;
54     value <<= shiftDistance;
55     *destination &= ~(bitmask(bit_count) << shiftDistance);
56     *destination |= value;
57     return true;
58 }