aboutsummaryrefslogtreecommitdiffstats
path: root/libs/bitfield-c/src/bitfield/8byte.c
blob: be46e825d7fc26b2a2f0e3d23c91ef8596972a94 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <bitfield/bitfield.h>
#include <bitfield/8byte.h>
#include <stddef.h>
#include <limits.h>
#include <string.h>

#define EIGHTBYTE_BIT (8 * sizeof(uint64_t))

unsigned int eightbyte_get_nibble(const uint64_t source, const unsigned int nibble_index,
        const bool data_is_big_endian) {
    return (unsigned int) eightbyte_get_bitfield(source, NIBBLE_SIZE * nibble_index,
            NIBBLE_SIZE, data_is_big_endian);
}

unsigned int eightbyte_get_byte(uint64_t source, const unsigned int byte_index,
        const bool data_is_big_endian) {
    if(data_is_big_endian) {
        source = __builtin_bswap64(source);
    }
    return (source >> (EIGHTBYTE_BIT - ((byte_index + 1) * CHAR_BIT))) & 0xFF;
}

// TODO is this funciton necessary anymore? is it any faster for uint64_t than
// get_bitfield(data[], ...)? is the performance better on a 32 bit platform
// like the PIC32?
uint64_t eightbyte_get_bitfield(uint64_t source, const unsigned int offset,
        const unsigned int bit_count, const bool data_is_big_endian) {
    int startByte = offset / CHAR_BIT;
    int endByte = (offset + bit_count - 1) / CHAR_BIT;

    if(!data_is_big_endian) {
        source = __builtin_bswap64(source);
    }

    unsigned int* bytes = (unsigned int*)&source;
    uint64_t ret = bytes[startByte];
    if(startByte != endByte) {
        // The lowest byte address contains the most significant bit.
        unsigned int i;
        for(i = startByte + 1; i <= endByte; i++) {
            ret = ret << 8;
            ret = ret | bytes[i];
        }
    }

    ret >>= 8 - find_end_bit(offset + bit_count);
    return ret & bitmask(bit_count);
}

bool eightbyte_set_bitfield(uint64_t value, const unsigned int offset,
        const unsigned int bit_count, uint64_t* destination) {
    if(value > bitmask(bit_count)) {
        return false;
    }

    int shiftDistance = EIGHTBYTE_BIT - offset - bit_count;
    value <<= shiftDistance;
    *destination &= ~(bitmask(bit_count) << shiftDistance);
    *destination |= value;
    return true;
}