I'm trying to write a C function that takes a uint64_t
and replace it's nth byte to a given one.
void setByte(uint64_t *bytes, uint8_t byte, pos)
I know I can easily get the nth byte like so
uint8_t getByte(uint64_t bytes, int pos)
{
return (bytes >> (8 * pos)) & 0xff;
}
But I have no idea how to Set the nth byte
Try this:
void setByte(uint64_t *bytes, uint8_t byte, int pos) {
*bytes &= ~((uint64_t)0xff << (8*pos)); // Clear the current byte
*bytes |= ((uint64_t)byte << (8*pos)); // Set the new byte
}
Use a mask to set every bit of the target byte to 0 (i.e. the mask should be all 1s but 0s at the target byte and then ANDed to the integer), then use another mask with all 0s but the intended value in the target byte and then OR it with the integer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With