d3160934e4744e89d359a11d71d11459df36e636
[apps/low-level-can-service.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 data_is_big_endian) {
15     return get_bit_field(source, NIBBLE_SIZE * nibble_index, NIBBLE_SIZE,
16             data_is_big_endian);
17 }
18
19 uint8_t eightbyte_get_byte(uint64_t source, const uint8_t byte_index,
20         const bool data_is_big_endian) {
21     if(data_is_big_endian) {
22         source = __builtin_bswap64(source);
23     }
24     return (source >> (EIGHTBYTE_BIT - ((byte_index + 1) * CHAR_BIT))) & 0xFF;
25 }
26
27 uint64_t get_bit_field(uint64_t source, const uint16_t offset,
28         const uint16_t bit_count, const bool data_is_big_endian) {
29     int startByte = offset / CHAR_BIT;
30     int endByte = (offset + bit_count - 1) / CHAR_BIT;
31
32     if(!data_is_big_endian) {
33         source = __builtin_bswap64(source);
34     }
35
36     uint8_t* bytes = (uint8_t*)&source;
37     uint64_t ret = bytes[startByte];
38     if(startByte != endByte) {
39         // The lowest byte address contains the most significant bit.
40         int i;
41         for(i = startByte + 1; i <= endByte; i++) {
42             ret = ret << 8;
43             ret = ret | bytes[i];
44         }
45     }
46
47     ret >>= 8 - find_end_bit(offset + bit_count);
48     return ret & bitmask(bit_count);
49 }
50
51 bool set_bit_field(uint64_t* destination, uint64_t value, const uint16_t offset,
52         const uint16_t bit_count) {
53     if(value > bitmask(bit_count)) {
54         return false;
55     }
56
57     int shiftDistance = EIGHTBYTE_BIT - offset - bit_count;
58     value <<= shiftDistance;
59     *destination &= ~(bitmask(bit_count) << shiftDistance);
60     *destination |= value;
61     return true;
62 }