Advantage of using 0x01 instead of 1 for an integer variable?

后端 未结 4 1838
我在风中等你
我在风中等你 2020-12-16 12:44

Recently I came across a line like this

public final static int DELETION_MASK = 0x01;

why is it not like

相关标签:
4条回答
  • 2020-12-16 13:16

    It helps with the mental conversion between the integer value and the bit pattern it represents, which is the thing that matters for flags and masks.

    Because 16 is a power of 2 (unlike 10), you get nice repeating things like this:

    public final static int A_FLAG = 0x01;  // 00000001
    public final static int B_FLAG = 0x02;  // 00000010
    public final static int C_FLAG = 0x04;  // 00000100
    public final static int D_FLAG = 0x08;  // 00001000
    public final static int E_FLAG = 0x10;  // 00010000
    public final static int F_FLAG = 0x20;  // 00100000
    public final static int G_FLAG = 0x40;  // 01000000
    public final static int H_FLAG = 0x80;  // 10000000
    
    0 讨论(0)
  • 2020-12-16 13:16

    Only that, it will be consistent when you define NONDELETION_MASK = 0x0A.

    0 讨论(0)
  • 2020-12-16 13:26

    It is easy to understand. Whenever we think about masking then we always think in HEX or BIN numbers.

    0 讨论(0)
  • 2020-12-16 13:29

    While there is not a difference in the code produced by the compiler, bit masks are traditionally written using the hexadecimal notation, because it's significantly easier for a human to convert to a binary form. Another common convention is to include the leading zeros when the length of the field is known. E.g. for a C int field, it's common to write:

    #define MASK 0x0000ffff
    

    In addition, hexadecimal constants indicate to the programmer that it's probably a bit mask, or a value that will be somehow involved in bitwise operations and should probably be treated specially.

    As a bonus, hexadecimal notations may also avoid issues with negative numbers: 0xffffffff is in fact a negative number (-1 to be exact). Rather than juggling with the sign and 2's-complement numbers you can just specify the mask in hexadecimal and be done with it.


    Since Java 7 you can also use binary literals which makes it even easier for a human to understand which bits are set in a bit mask. And binary literals may make use of underscores to put the bits into separate groups.

    That means that the following is also valid:

    public final static int DELETION_MASK = 0b0000_0001;
    
    0 讨论(0)
提交回复
热议问题