diff options
author | Christopher Peplin <chris.peplin@rhubarbtech.com> | 2013-12-29 12:06:11 -0500 |
---|---|---|
committer | Christopher Peplin <chris.peplin@rhubarbtech.com> | 2013-12-29 12:06:11 -0500 |
commit | f29f8a4cefbdc798c4a9aba495da7d2c0a81774c (patch) | |
tree | c3ec6e1cc8c75f30c4341812c3a7ad31445c51d9 /src/bitfield | |
parent | c2c7ef1dfe4cae6b5831ffab0ce5780b27e0c25e (diff) |
Check if a value will fit in bitfield before setting.
Diffstat (limited to 'src/bitfield')
-rw-r--r-- | src/bitfield/8byte.c | 11 | ||||
-rw-r--r-- | src/bitfield/8byte.h | 5 |
2 files changed, 10 insertions, 6 deletions
diff --git a/src/bitfield/8byte.c b/src/bitfield/8byte.c index 77251996..3b6b5466 100644 --- a/src/bitfield/8byte.c +++ b/src/bitfield/8byte.c @@ -40,16 +40,17 @@ uint64_t get_bit_field(uint64_t source, const uint16_t startBit, 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 set_bit_field(uint64_t* destination, uint64_t value, const uint16_t offset, +bool set_bit_field(uint64_t* destination, uint64_t value, const uint16_t offset, const uint16_t bit_count) { + 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; } uint8_t nth_byte(const uint64_t source, const uint16_t byte_index) { diff --git a/src/bitfield/8byte.h b/src/bitfield/8byte.h index 9cbf61a9..36b5fe60 100644 --- a/src/bitfield/8byte.h +++ b/src/bitfield/8byte.h @@ -55,8 +55,11 @@ uint64_t get_bit_field(uint64_t source, const uint16_t offset, * value - the value to set in the bit field. * offset - the starting index of the bit field (beginning from 0). * bit_count - the number of bits to set in the data. + * + * Returns true if the bit_count is enough to fully represent the value, and + * false if it will not fit. */ -void set_bit_field(uint64_t* destination, uint64_t value, const uint16_t offset, +bool set_bit_field(uint64_t* destination, uint64_t value, const uint16_t offset, const uint16_t bit_count); /* Public: Retreive the nth byte out of 8 bytes in a uint64_t. |