Initializing byte variables with hex numbers in Java | SoloLearn: Learn to code for FREE!

+1

Initializing byte variables with hex numbers in Java

I am trying to initialize or assign a hex number to a byte variable. Whenever I do: byte c = 0xFF; Compiler throws an error. But when I do: byte c = 0xFFFFFFFF; Compiler doesn't throw an error. I think it is related to the int s which are 32 bits. Could you tell it why it is so?

5/11/2019 12:56:34 PM

Yusuf

1 Answer

New Answer

+1

byte is signed, possible values are from Byte.MAX_VALUE == 127 Byte.MIN_VALUE == -128 literal numbers are processed as signed integer 0xFF is 255 and is not accepted 0xFFFFFFFF is -1 and is accepted to assigned to byte type byte c =0xFFFFFFFF; System.out.println(c); // -1 (byte) 0xff // -1 int i = Byte.toUnsignedInt( (byte) 0xFF ); //255 Byte.SIZE; //8 Byte.BYTES; // 1