Solidity bitwise operation changing a number does not update correctly

Viewed 94

So I am packing 32 uint8 into a uint256 using bitmap, however when I'm trying to change a value of uint8, it does not update correctly. For example when changing 222 to 221, it becomes 223, I have some idea on why it's happening but I don't know what is the correct way to update it, is it correct to change the uint8 to 0 first then update it? how is it done?

uint256 bitmap;
// setting the value for the first time
bitmap |= 222>>0;
bitmap |= 150>>8; 
// and so on...

// updating the value
bitmap |= 221<<0; // when calling this, it becomes 223

// tried to change the value to 0 first
bitmap &= ~(1<<0);
bitmap |= 221<<0;
// still becomes 223

Might still not really understand how bitwise operator works, how do I update the value?

1 Answers

222 is binary 1101 1110

221 is binary 1101 1101

When you do 222 or 221 and assign it to bitmap, both the second rightmost bit and the rightmost bits become 1, and therefore it becomes

223, 1101 1111

There are many ways you can change a specific byte in an integer, but this can help:

bitmap &= ~(0xFF << 0) | (221 << 0) // change 0 to byte index, 0 is the rightmost byte
Related