Initializing byte variables with hex numbers in Java | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 2

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?

11th May 2019, 12:56 PM
Yusuf
Yusuf - avatar
1 Antwort
+ 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
12th May 2019, 5:24 PM
zemiak