如何将一个字节存储到 4 字节数字中而不更改其周围的字节?
因此,如果我有一个 4 字节数字(例如十六进制),并且想要将一个字节(例如 DD)存储到十六进制中的第 n 个字节位置,而不更改十六进制数字的其他元素,那么最简单的方法是什么?我猜这是按位运算的某种组合,但我对它们仍然很陌生,并且到目前为止发现它们很混乱?
So if I have a 4 byte number (say hex) and 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
编辑:忘记提及,如果您使用带符号的数据类型执行此操作,请务必小心,以免无意中进行符号扩展。
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 的答案展示了如何通过位操作来做到这一点。您还可以使用旧的字节数组技巧(假设 C 或其他允许这种愚蠢的语言):
当然,这是特定于处理器的,因为大端机器的字节与小端相反。此外,该技术限制您在精确的字节边界上工作,而位操作将允许您修改任何给定的 8 位。也就是说,您可能希望将
0x12345678
转换为0x12345DD8
,但我展示的技术无法做到这一点。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):
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
into0x12345DD8
, which the technique I show won't do.