Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Replacing the nth byte of a 64 bit integer [duplicate]

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

like image 659
angauber Avatar asked Oct 17 '25 06:10

angauber


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
}
like image 60
Daniel Walker Avatar answered Oct 18 '25 21:10

Daniel Walker


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.

like image 32
Sufian Latif Avatar answered Oct 18 '25 21:10

Sufian Latif



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!