某种编码?
如果以前有人问过这个问题,请原谅我,但我向你保证,我已经在互联网上搜索过,但什么也没找到,可能是因为我没有正确的术语。
我想获取一个整数并将其转换为小端(?)十六进制表示形式,如下所示:
303 -> 0x2f010000
我可以看到字节被打包,使得16位和1位都在同一个字节中,并且4096位和256位共享一个字节。 如果有人可以向我指出此类编码的正确术语,我相信我可以找到如何做到这一点的答案。 谢谢!
Forgive me if this has been asked before, but I assure you I've scoured the internet and have turned up nothing, probably because I don't have the right terminology.
I would like to take an integer and convert it to a little-endian(?) hex representation like this:
303 -> 0x2f010000
I can see that the bytes are packed such that the 16's and 1's places are both in the same byte, and that the 4096's place and 256's place share a byte. If someone could just point me to the right terminology for such encoding, I'm sure I could find my answer on how to do it. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用位移运算符与按位 AND 和 OR 运算符相结合...
假设 32 位无符号:
use bit shift operators combined with bitwise AND and OR operators...
assuming 32 bit unsigned:
大端和小端是指内存中字节的顺序。 像 0x2f100000 这样的值没有内在的字节顺序,字节顺序取决于 CPU 架构。
如果您总是想反转 32 位值中的字节顺序,请使用 Demi 发布的代码。
如果您始终想要获取特定的字节顺序(因为您准备通过网络传输这些字节,或将它们存储到磁盘文件中),请使用其他内容。 例如,BSD 套接字库有一个函数 htonl(),它获取 CPU 的本机 32 位值并将其放入大端顺序。
如果您在小端机器上运行,则 htonl(303) == 0x2f100000。 如果您在大端机器上运行,则 htonl(303) == 303。在这两种情况下,结果都将由内存中的字节 [0x00, 0x00, 0x01, 0x2f] 表示。
Big-endian and little-endian refer to the order of the bytes in memory. A value like 0x2f100000 has no intrinsic endianness, endianness depends on the CPU architecture.
If you always want to reverse the order of the bytes in a 32-bit value, use the code that Demi posted.
If you always want to get the specific byte order (because you're preparing to transfer those bytes over the network, or store them to a disk file), use something else. E.g. the BSD sockets library has a function htonl() that takes your CPU's native 32-bit value and puts it into big-endian order.
If you're running on a little-endian machine, htonl(303) == 0x2f100000. If you're running on a big-endian machine, htonl(303) == 303. In both cases the result will be represented by bytes [0x00, 0x00, 0x01, 0x2f] in memory.
如果有人可以用一个具体的术语来描述我想要做的事情,我仍然很想听听。 然而,我确实找到了一种方法来完成我需要的事情,我将其发布在这里,这样如果有人来关注我,他们就可以找到它。 可能有(可能是)一种更简单、更直接的方法来做到这一点,但这就是我最终在 VB.Net 中所做的事情,以获取我想要的字节码:
有效地将整数分解为其十六进制分量,然后转换适当的对到 cByte。
If anyone can put a specific term to what I was trying to do, I'd still love to hear it. I did, however, find a way to do what I needed, and I'll post it here so if anyone comes looking after me, they can find it. There may be (probably is) an easier, more direct way to do it, but here's what I ended up doing in VB.Net to get back the bytecode I wanted:
Effectively breaking the integer up into its hex components, then converting the appropriate pairs to cBytes.