When is it necessary to expose hexadecimal literals in java (bytes)?

For testing purposes, I tried to create an array like this:

byte[] expected = new byte[]{0x2f, 0x0d4, 0xe1, 0xc6, 0x7a, 0x2d, 0x28, 0xfc} 

I expected java to complain and ask me to write every literal here (bytes), but suddenly he asked me to only convert 0x4d, but not 0x2f. Working example:

 new byte[]{0x2f, (byte) 0xd4, (byte) 0xe1, (byte) 0xc6, 0x7a, 0x2d, 0x28, (byte) 0xfc} 

How it works?

+4
source share
3 answers

I suspect this is because the Java byte is signed, so you have a range from -128 to 127. Thus, all values> 127 (0x80) must be explicitly converted.

+8
source

A linear number without l , d or f is an int value, so values ​​of 0x80 or more must be cast. One way to cover many hexadecimal values ​​is to use the following

 byte[] bytes = new BigInteger("2fd4e1c67a2d28fc", 16).toByteArray(); System.out.println(Arrays.toString(bytes)); 

prints

 [47, -44, -31, -58, 122, 45, 40, -4] 

This avoids some tedious , (byte) 0x between values.

+4
source

An integer literal between -128 to 127 will be automatically converted to the target type, and Java has only signed types.

+2
source

Source: https://habr.com/ru/post/1387720/


All Articles