Why use hex?

前端 未结 12 2020
你的背包
你的背包 2020-11-28 03:45

Hey! I was looking at this code at http://www.gnu.org/software/m68hc11/examples/primes_8c-source.html

I noticed that in some situations they used hex numbers, like i

12条回答
  •  清歌不尽
    2020-11-28 04:09

    In both cases you cite, the bit pattern of the number is important, not the actual number.

    For example, In the first case, j is going to be 1, then 2, 4, 8, 16, 32, 64 and finally 128 as the loop progresses.

    In binary, that is,

    0000:0001, 0000:0010, 0000:0100, 0000:1000, 0001:0000, 0010:0000, 0100:0000 and 1000:0000.

    There's no option for binary constants in C or C++, but it's a bit clearer in Hex: 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, and 0x80.

    In the second example, the goal was to remove the lower two bytes of the value. So given a value of 1,234,567,890 we want to end up with 1,234,567,168.
    In hex, it's clearer: start with 0x4996:02d2, end with 0x4996:0000.

提交回复
热议问题