bitfield-c: use unsigned int instead of uint8_t
[apps/agl-service-can-low-level.git] / libs / bitfield-c / 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 unsigned int eightbyte_get_nibble(const uint64_t source, const unsigned int nibble_index,
10         const bool data_is_big_endian) {
11     return (unsigned int) eightbyte_get_bitfield(source, NIBBLE_SIZE * nibble_index,
12             NIBBLE_SIZE, data_is_big_endian);
13 }
14
15 unsigned int eightbyte_get_byte(uint64_t source, const unsigned int 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 // TODO is this funciton necessary anymore? is it any faster for uint64_t than
24 // get_bitfield(data[], ...)? is the performance better on a 32 bit platform
25 // like the PIC32?
26 uint64_t eightbyte_get_bitfield(uint64_t source, const unsigned int offset,
27         const unsigned int bit_count, const bool data_is_big_endian) {
28     int startByte = offset / CHAR_BIT;
29     int endByte = (offset + bit_count - 1) / CHAR_BIT;
30
31     if(!data_is_big_endian) {
32         source = __builtin_bswap64(source);
33     }
34
35     unsigned int* bytes = (unsigned int*)&source;
36     uint64_t ret = bytes[startByte];
37     if(startByte != endByte) {
38         // The lowest byte address contains the most significant bit.
39         unsigned int i;
40         for(i = startByte + 1; i <= endByte; i++) {
41             ret = ret << 8;
42             ret = ret | bytes[i];
43         }
44     }
45
46     ret >>= 8 - find_end_bit(offset + bit_count);
47     return ret & bitmask(bit_count);
48 }
49
50 bool eightbyte_set_bitfield(uint64_t value, const unsigned int offset,
51         const unsigned int bit_count, uint64_t* destination) {
52     if(value > bitmask(bit_count)) {
53         return false;
54     }
55
56     int shiftDistance = EIGHTBYTE_BIT - offset - bit_count;
57     value <<= shiftDistance;
58     *destination &= ~(bitmask(bit_count) << shiftDistance);
59     *destination |= value;
60     return true;
61 }