52f368f5ce90fa1c31d1d5a8017272fad35e0826
[apps/agl-service-can-low-level.git] / src / bitfield / bitfield.c
1 #include <bitfield/bitfield.h>
2 #include <limits.h>
3 #include <string.h>
4 #include <stddef.h>
5 #include <endian.h>
6
7 uint64_t bitmask(const uint8_t bit_count) {
8     return (((uint64_t)0x1) << bit_count) - 1;
9 }
10
11 uint8_t get_nibble(const uint8_t source[], const uint8_t source_length,
12                 const uint8_t nibble_index) {
13     uint8_t byte_index = nibble_index / 2;
14     uint8_t result = get_byte(source, source_length, byte_index);
15     if(nibble_index % 2 == 0) {
16         result >>= NIBBLE_SIZE;
17     }
18     result &= bitmask(NIBBLE_SIZE);
19     return result;
20 }
21
22 uint8_t get_byte(const uint8_t source[], const uint8_t source_length,
23         const uint8_t byte_index) {
24     if(byte_index < source_length) {
25         return source[byte_index];
26     }
27     return 0;
28 }
29
30 uint64_t get_bitfield(const uint8_t source[], const uint8_t source_length,
31                 const uint16_t offset, const uint16_t bit_count) {
32     if(bit_count > 64 || bit_count < 1) {
33         // TODO error reporting?
34         return 0;
35     }
36
37     union {
38         uint64_t whole;
39         uint8_t bytes[sizeof(uint64_t)];
40     } combined;
41     copy_bits_right_aligned(source, source_length, offset, bit_count,
42             combined.bytes, sizeof(combined.bytes));
43     return htobe64(combined.whole);
44 }
45
46 bool set_nibble(const uint16_t nibble_index, const uint8_t value,
47         uint8_t* destination, const uint16_t destination_length) {
48     return copy_bits(&value, CHAR_BIT, NIBBLE_SIZE, NIBBLE_SIZE, destination,
49             destination_length, nibble_index * NIBBLE_SIZE);
50 }
51