Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why byte b = (byte) 0xFF is equals to integer -1?

Tags:

Why byte b = (byte) 0xFF is equal to integer -1?

Ex:

int value = byte b = (byte) 0xFF; System.out.println(value); 

it will print -1?

like image 994
okami Avatar asked Nov 05 '09 02:11

okami


People also ask

Is 0xff one byte?

Representing 0xff With Different Data Types int x = 0xff; assertEquals(255, x); However, if we define a byte variable with the value 0xff, since Java represents a byte using 8 bits and because a byte is a signed data type, the value of 0xff is -1: byte y = (byte) 0xff; assertEquals(-1, y);

Is 0xff positive or negative?

So, for example, binary 10000010 represents decimal 130 (128+2) if it's unsigned, but -126 (-128+2) if that same value is signed. Negative one is 0xff, since 64+32+16+8+4+2+1==127.

What does 0xff mean in C++?

0xff means "the hexadecimal number ff " - in other words, the integer 255 , which has the binary representation 00000000000000000000000011111111 (when using 32-bit integers). The & operator performs a bitwise AND operation.

Why a byte is 127 to 128?

This is because we have to represent the number 0, so inclusively 0-127 is the other 128 possibilities of our range. If we were only allowing positive values, such as an unsigned byte where negative numbers aren't possible, the range would be 0-255, since these are 256 different values (including the 0).


2 Answers

Bytes are signed in Java. In binary 0x00 is 0, 0x01 is 1 and so on but all 1s (ie 0xFF) is -1, 0xFE is -2 and so on. See Two's complement, which is the binary encoding mechanism used.

like image 86
cletus Avatar answered Sep 19 '22 09:09

cletus


  1. b is promoted to an int in determining which overload of system.out.println to call.

  2. All bytes in Java are signed.

  3. The signed byte 0xff represents the value -1. This is because Java uses two's complement to represent signed values. The signed byte 0xff represents -1 because its most significant bit is 1 (so therefore it represents a negative value) and its value is -128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = -1.

like image 37
jason Avatar answered Sep 21 '22 09:09

jason