1 #include <bitfield/bitfield.h>
2 #include <bitfield/8byte.h>
7 #define EIGHTBYTE_BIT (8 * sizeof(uint64_t))
9 uint64_t bitmask(const uint8_t bit_count) {
10 return (((uint64_t)0x1) << bit_count) - 1;
13 static uint16_t bits_to_bytes(uint32_t bits) {
14 uint8_t byte_count = bits / CHAR_BIT;
15 if(bits % CHAR_BIT != 0) {
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;
27 source = __builtin_bswap64(source);
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.
35 for(i = startByte + 1; i <= endByte; i++) {
41 ret >>= 8 - find_end_bit(offset + bit_count);
42 return ret & bitmask(bit_count);
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)) {
51 int shiftDistance = EIGHTBYTE_BIT - offset - bit_count;
52 value <<= shiftDistance;
53 *destination &= ~(bitmask(bit_count) << shiftDistance);
54 *destination |= value;
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;