C - 二进制和十六进制表示之间的快速转换
阅读或编写 C 代码时,我经常难以将数字从二进制表示形式转换为十六进制表示形式并返回。通常,诸如0xAAAA5555
之类的不同掩码在低级编程中经常使用,但很难识别它们所代表的特殊位模式。有没有什么容易记住的规则,如何快速地在脑海中完成?
Reading or writing a C code, I often have difficulties translating the numbers from the binary to the hex representations and back. Usually, different masks like 0xAAAA5555
are used very often in low-level programming, but it's difficult to recognize a special pattern of bits they represent. Is there any easy-to-remember rule how to do it fast in the mind?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
每个十六进制数字精确地映射在 4 位上,我通常会记住每个位的 8421 个权重,因此即使是心中有数的转换也很容易,即
A = 10 = 8+2 = 1010 ...
5 = 4+1 = 0101
只需记住 8-4-2-1 权重即可。
Each hex digit map exactly on 4 bit, I usually keep in mind the 8421 weights of each of these bits, so it is very easy to do even an in mind conversion ie
A = 10 = 8+2 = 1010 ...
5 = 4+1 = 0101
just keep the 8-4-2-1 weights in mind.
我总是发现很容易将十六进制映射到二进制数字。由于每个十六进制数字都可以直接映射到四位二进制数字,
因此您可以认为:
I always find easy to map HEX to BINARY numbers. Since each hex digit can be directly mapped to a four digit binary number, you can think of:
As
通过将以 10 为基数的表示形式除以 2 并将余数按相反顺序排列来计算转换。我在脑子里这样做,似乎有效。
所以你说
0xAAAA5555
看起来像什么,我只是通过这样做算出了 A 的样子和 5 的样子
,所以我知道 A 看起来像
1010
(请注意,4 根手指是记住余数的好方法!)您可以将 4 位块串在一起,因此 AA 是 1010 1010。要将二进制转换回十六进制,我总是通过求和再次遍历基数 10 2 的幂。您可以通过形成 4 位块(用 0 填充)并将结果串起来来完成此操作。
所以
111011101
是0001 1101 1101
也就是(1) (1 + 4 + 8) (1 + 4 + 8) = 1 13 13
这是1DD
The conversion is calculated by dividing the base 10 representation by 2 and stringing the remainders in reverse order. I do this in my head, seems to work.
So you say what does
0xAAAA5555
look likeI just work out what A looks like and 5 looks like by doing
so I know the A's look like
1010
(Note that 4 fingers are a good way to remember the remainders!)You can string blocks of 4 bits together, so A A is 1010 1010. To convert binary back to hex, I always go through base 10 again by summing up the powers of 2. You can do this by forming blocks of 4 bits (padding with 0s) and string the results.
so
111011101
is0001 1101 1101
which is(1) (1 + 4 + 8) (1 + 4 + 8) = 1 13 13
which is1DD