开发者

How do I store a byte into a 4 byte number without changing the bytes around it?

So if I have a 4 byte number (say hex) an开发者_Go百科d want to store a byte say DD into hex, at the nth byte position without changing the other elements of hex's number, what's the easiest way of going about that? I'm guessing it's some combination of bitwise operations, but I'm still quite new with them, and have found them quite confusing thus far?


byte n = 0xDD;
uint i = 0x12345678;
i = (i & ~0x0000FF00) | ((uint)n << 8);

Edit: Forgot to mention, be careful if you're doing this with signed data types, so that things don't get inadvertently sign-extended.


Mehrdad's answer shows how to do it with bit manipulation. You could also use the old byte array trick (assuming C or some other language that allows this silliness):

byte n = 0xDD;
uint i = 0x12345678;
byte *b = (byte*)&i;
b[1] = n;

Of course, that's processor specific in that big-endian machines have the bytes reversed from little-endian. Also, this technique limits you to working on exact byte boundaries whereas the bit manipulation will let you modify any given 8 bits. That is, you might want to turn 0x12345678 into 0x12345DD8, which the technique I show won't do.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜