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