Add a function to set a single nibble in a bitarray.
[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
6 uint8_t get_nibble(const uint8_t source[], const uint8_t source_length,
7                 const uint8_t nibble_index) {
8     uint8_t byte_index = nibble_index / 2;
9     uint8_t result = get_byte(source, source_length, byte_index);
10     if(nibble_index % 2 == 0) {
11         result >>= NIBBLE_SIZE;
12     }
13     result &= bitmask(NIBBLE_SIZE);
14     return result;
15 }
16
17 uint8_t get_byte(const uint8_t source[], const uint8_t source_length,
18         const uint8_t byte_index) {
19     if(byte_index < source_length) {
20         return source[byte_index];
21     }
22     return 0;
23 }
24
25 bool set_nibble(const uint16_t nibble_index, const uint8_t value,
26         uint8_t* destination, const uint16_t destination_length) {
27     return copy_bits(&value, CHAR_BIT, NIBBLE_SIZE, NIBBLE_SIZE, destination,
28             destination_length, nibble_index * NIBBLE_SIZE);
29 }