0

I have a question about initializing byte in java, I want to initialize a byte value allBitsOne and all bits of it are 1:

Method 1:

byte allBitsOne = 0xFF;

Wrong, it says that 0xFF is a integer type and over the range of byte, so i do it like below

Method 2:

byte allBitsOne = (byte)0xFF; 

Works fine.

Method 3:

byte allBitsOne = 0xFFFFFFFF; 

It works fine as well, but if 0xFF exceeds the range of a byte, why doesn't 0xFFFFFFFF?

Thank you all, I found this: link

Community
  • 1
  • 1
hsy0
  • 139
  • 1
  • 9

3 Answers3

4

byte is a signed integer type, going from -128 to 127.

0xFF is 255, so it's larger than 127.

0xFFFFFFFF is -1, so it's within the bounds of the byte type.

See http://en.wikipedia.org/wiki/Two%27s_complement

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
1

literal integers in Java are signed 32 bit numbers, so:

0xff is an integer type which equals to 255, which is over the limit for byte.

0xffffffff is an integer type which equals to -1, which is not over the limit for byte.

MByD
  • 135,866
  • 28
  • 264
  • 277
1

the byte-variable in the java in the java can hold the values from -128 to 127. if you want to set all the bit to 1. then u can store the -128 to it.

Karthikeyan Sukkoor
  • 968
  • 2
  • 6
  • 24