C - 二进制和十六进制表示之间的快速转换

发布于 2025-01-06 06:41:14 字数 138 浏览 0 评论 0原文

阅读或编写 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

゛清羽墨安 2025-01-13 06:41:14

每个十六进制数字精确地映射在 4 位上,我通常会记住每个位的 8421 个权重,因此即使是心中有数的转换也很容易,即

A = 10 = 8+2 = 1010 ...
5 = 4+1 = 0101

只需记住 8-4-2-1 权重即可。

A        5     
8+4+2+1  8+4+2+1
1 0 1 0  0 1 0 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.

A        5     
8+4+2+1  8+4+2+1
1 0 1 0  0 1 0 1
滿滿的愛 2025-01-13 06:41:14

我总是发现很容易将十六进制映射到二进制数字。由于每个十六进制数字都可以直接映射到四位二进制数字

> 0xA4 

因此您可以认为:

> b 1010 0100
>   ---- ---- (4 binary digits for each part)
>     A    4

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:

> 0xA4 

As

> b 1010 0100
>   ---- ---- (4 binary digits for each part)
>     A    4
恋竹姑娘 2025-01-13 06:41:14

通过将以 10 为基数的表示形式除以 2 并将余数按相反顺序排列来计算转换。我在脑子里这样做,似乎有效。

所以你说 0xAAAA5555 看起来像什么,

我只是通过这样做算出了 A 的样子和 5 的样子

A = 10

10 / 2 = 5 r 0 
 5 / 2 = 2 r 1
 2 / 2 = 1 r 0
 1 / 2 = 0 r 1

,所以我知道 A 看起来像 1010 (请注意,4 根手指是记住余数的好方法!)

您可以将 4 位块串在一起,因此 AA 是 1010 1010。要将二进制转换回十六进制,我总是通过求和再次遍历基数 10 2 的幂。您可以通过形成 4 位块(用 0 填充)并将结果串起来来完成此操作。

所以 1110111010001 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 like

I just work out what A looks like and 5 looks like by doing

A = 10

10 / 2 = 5 r 0 
 5 / 2 = 2 r 1
 2 / 2 = 1 r 0
 1 / 2 = 0 r 1

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 is 0001 1101 1101 which is (1) (1 + 4 + 8) (1 + 4 + 8) = 1 13 13 which is 1DD

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文