Replace byte in a int

最后都变了- 提交于 2019-12-04 12:10:53

No, no bytes arrays. This actually very simple.

Not tested:

int ReplaceByte(int index, int value, byte replaceByte)
{
    return (value & ~(0xFF << (index * 8))) | (replaceByte << (index * 8));
}

First it clears the space where at the specified index, and then it puts the new value in that space.

You can simply use some bitwise arithmetic:

// how many bits you should shift replaceByte to bring it "in position"
var shiftBits = 8 * index;

// bitwise AND this with value to clear the bits that should become replaceByte
var mask = ~(0xff << shiftBits);

// clear those bits and then set them to whatever replaceByte is
return value & mask | (replaceByte << shiftBits);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!