From 6ce03a4f1b229e605da08b073fad6f7c0fe8bf10 Mon Sep 17 00:00:00 2001 From: Christopher Peplin Date: Sun, 29 Dec 2013 11:48:24 -0500 Subject: Split up 8 byte wrappers from generic bit array functions. --- src/bitfield/8byte.c | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 src/bitfield/8byte.c (limited to 'src/bitfield/8byte.c') diff --git a/src/bitfield/8byte.c b/src/bitfield/8byte.c new file mode 100644 index 0000000..0f249d9 --- /dev/null +++ b/src/bitfield/8byte.c @@ -0,0 +1,56 @@ +#include +#include +#include +#include +#include + +uint64_t bitmask(const uint8_t numBits) { + return (((uint64_t)0x1) << numBits) - 1; +} + +static uint16_t bitsToBytes(uint32_t bits) { + uint8_t byte_count = bits / CHAR_BIT; + if(bits % CHAR_BIT != 0) { + ++byte_count; + } + return byte_count; +} + +uint64_t getBitField(uint64_t data, const uint16_t startBit, + const uint16_t numBits, bool bigEndian) { + uint8_t result[8] = {0}; + if(!bigEndian) { + data = __builtin_bswap64(data); + } + copyBitsRightAligned((const uint8_t*)&data, sizeof(data), startBit, numBits, + result, sizeof(result)); + uint64_t int_result = 0; + + if(!bigEndian) { + // we need to swap the byte order of the array to get it into a + // uint64_t, but it's been right aligned so we have to be more careful + for(int i = 0; i < bitsToBytes(numBits); i++) { + int_result |= result[bitsToBytes(numBits) - i - 1] << (CHAR_BIT * i); + } + } else { + int_result = *(uint64_t*)result; + } + return int_result; +} + +/** + * TODO it would be nice to have a warning if you call with this a value that + * won't fit in the number of bits you've specified it should use. + */ +void setBitField(uint64_t* data, uint64_t value, const uint16_t startPos, + const uint16_t numBits) { + int shiftDistance = 64 - startPos - numBits; + value <<= shiftDistance; + *data &= ~(bitmask(numBits) << shiftDistance); + *data |= value; +} + +uint8_t nthByte(const uint64_t source, const uint16_t byteNum) { + return (source >> (64 - ((byteNum + 1) * CHAR_BIT))) & 0xFF; +} + -- cgit 1.2.3-korg