Why use hexadecimal constants?

后端 未结 11 930
挽巷
挽巷 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 13:51

    Sometimes it's easier using bit-related algorithms. Other times, it deals with bit comparisons, as my statement in a comment, 4 bits (binary digits) convert to 1 hex letter, so, A3 = 10100011.

    Other times, it's either fun or breaks the monotony, though people not familiar with hex may think that you are doing things with pointers

    int data = 0xF00D;
    if ( val != 0xC0FFEE )
    {
       data = 0xDECAF;
    }
    

    I sometimes use it to check bounds of things like ints. For example, you can use 0x7FFFFFFF (0x80000000 works in many cases but the 0x7F... is safer) to get a max int bounds. It's handy for setting a very high error constant if you don't have a language that has something like MAX_INT. The technique scales as well, since for 64-bit, you can use 0x7FFFFFFFFFFFFFFF. You may notice that Android uses 0x7___ for R.id table look-ups.

    I bet they are doing it for clarity's sake. You can easily use integers, but if you are familiar with hex, it's not bad. It looks like they are reserving x values for certain functions. In decimal, you would do something like 0-99 is errors, 100-199 for something else, and so forth. How they are doing it is scaled differently.

    Performance-wise, you gain nothing at runtime since the compiler (even a lot of assemblers) converts whatever format to binary in the end, whether decimal, octal, hexadecimal, float, double, etc.

提交回复
热议问题