Hexadecimal notation and signed integers

后端 未结 3 776
一生所求
一生所求 2021-01-11 15:33

This is a follow up question. So, Java store\'s integers in two\'s-complements and you can do the following:

int ALPHA_MASK = 0xff000000;

I

相关标签:
3条回答
  • 2021-01-11 16:15

    C# (rather, .NET) also uses the two's complement, but it supports both signed and unsigned types (which Java doesn't). A bit mask is more naturally an unsigned thing - why should one bit be different than all the other bits?

    In this specific case, it is safe to use an unchecked cast:

    int ALPHA_MASK = unchecked((int)0xFF000000);
    

    To "directly" represent this number as a signed value, you write

    int ALPHA_MASK = -0x1000000; // == -16777216
    

    Hexadecimal is not (or should not) be any different from decimal: to represent a negative number, you need to write a negative sign, followed by the digits representing the absolute value.

    0 讨论(0)
  • 2021-01-11 16:29

    And just to add insult to injury, this will work too:

    -0x7F000000
    
    0 讨论(0)
  • 2021-01-11 16:33

    Well, you can use an unchecked block and a cast:

    unchecked
    {
        int ALPHA_MASK = (int)0xff000000;
    }
    

    or

    int ALPHA_MASK = unchecked((int)0xff000000);
    

    Not terribly convenient, though... perhaps just use a literal integer?

    0 讨论(0)
提交回复
热议问题