Why use hex?

前端 未结 12 2001
你的背包
你的背包 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:08

    The single biggest use of hex is probably in embedded programming. Hex numbers are used to mask off individual bits in hardware registers, or split multiple numeric values packed into a single 8, 16, or 32-bit register.

    When specifying individual bit masks, a lot of people start out by:

    #define bit_0 1
    #define bit_1 2
    #define bit_2 4
    #define bit_3 8
    #define bit_4 16
    etc...
    

    After a while, they advance to:

    #define bit_0 0x01
    #define bit_1 0x02
    #define bit_2 0x04
    #define bit_3 0x08
    #define bit_4 0x10
    etc...
    

    Then they learn to cheat, and let the compiler generate the values as part of compile time optimization:

    #define bit_0 (1<<0)
    #define bit_1 (1<<1)
    #define bit_2 (1<<2)
    #define bit_3 (1<<3)
    #define bit_4 (1<<4)
    etc...
    

提交回复
热议问题