Understanding Java unsigned numbers

后端 未结 3 982
礼貌的吻别
礼貌的吻别 2021-01-03 00:59

I want to understand how to convert signed number into unsigned.

lets say I have this:

byte number = 127; // \'1111111\'

In order t

相关标签:
3条回答
  • 2021-01-03 01:37

    Java doesn't actually have unsigned primitives.

    The value 127 is actually represented by '01111111' the first bit being the sign (0 is positive).

    An unsigned byte would be able to hold values 0 to 255, but 127 is the maximum for a signed byte. Since a byte has 8 bits, and the signed one consumes one to hold the sign. So if you want to represent values larger than 127 you need to use a bigger type that has a greater number of bits. The greater type also has a reserved bit for sign, but it has at least 8 bits used for the actual values, so you can represent the value 255.

    That being said, you should probably avoid using byte and short because there are issues with them. You'll notice i cast the result to short, since the operators actually return int. You should just stick to int and long in java since they are implemented better.

    Edit: the AND operator makes it unsigned since the sign bit is the first bit of the short, and you copy the 8 bits holding the value of the byte to the last 8 bits of the short. So if you have a negative number the first bit which is 1 (that means it's negative) actually becomes part of the value. And the short will always be positive since its sign bit is at two high of a power of two to be affected by the short.

     byte:             10101101
                        ||||||| <- actual value
    short:     0000000010101101
                ||||||||||||||| <- actual value
    

    Edit 2: Take note though that since the negative values use two's complement representation the value might not be what you expect it. all the positive values remain the same.
    But -128 = 0x10000000 will become 128
    -127 = 0x10000001 will become 129
    and so on until -1 = 0x11111111 which will become 255

    0 讨论(0)
  • 2021-01-03 01:39

    java does not have unsigned data types. You just make switch to "bigger" data type, that's all.

    0 讨论(0)
  • 2021-01-03 02:01

    If you just move from a negative byte to int the int will be negative too. Sou you take the negative int (or short in your example) and set the highest 3 byte (int) to 0x00.

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