3

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

angauber
  • 43
  • 5

2 Answers2

3

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
}
Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
2

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.

Sufian Latif
  • 13,086
  • 3
  • 33
  • 70