Why use hexadecimal constants?

后端 未结 11 971
挽巷
挽巷 2020-12-07 13:16

Sometimes I see Integer constants defined in hexadecimal, instead of decimal numbers. This is a small part I took from a GL10 class:

public static final int          


        
11条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-07 14:07

    There will be no performance gain between a decimal number and a hexadecimal number, because the code will be compiled to move byte constants which represent numbers.

    Computers don't do decimal, they do (at best) binary. Hexadecimal maps to binary very cleanly, but it requires a bit of work to convert a decimal number to binary.

    One place where hexadecimal shines is when you have a number of related items, where many are similar, yet slightly different.

    // These error flags tend to indicate that error flags probably
    // all start with 0x05..
    public static final int GL_STACK_UNDERFLOW = 0x0504;
    public static final int GL_OUT_OF_MEMORY = 0x0505;
    
    // These EXP flags tend to indicate that EXP flags probably
    // all start with 0x08..
    public static final int GL_EXP = 0x0800;
    public static final int GL_EXP2 = 0x0801;
    
    // These FOG flags tend to indicate that FOG flags probably
    // all start with 0x0B.., or maybe 0x0B^.
    public static final int GL_FOG_DENSITY = 0x0B62;
    public static final int GL_FOG_START = 0x0B63;
    public static final int GL_FOG_END = 0x0B64;
    public static final int GL_FOG_MODE = 0x0B65;
    

    With decimal numbers, one would be hard pressed to "notice" constant regions of bits across a large number of different, but related items.

提交回复
热议问题