C - Replacing the nth byte of a 64 bit integer

Viewed 555

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

2 Answers

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.

Related