Literary syntax For bytes [] of arrays using hexadecimal notation ..?

The compiler seems to agree with this (only single-valued hexadecimal values):

byte[] rawbytes={0xa, 0x2, 0xf}; 

But not this:

 byte[] rawbytes={0xa, 0x2, 0xff}; 

I get the error "Possible loss of accuracy": int error required: byte "

What am I doing wrong - or is it single digits of hexadecimal numbers in a special case?

Java 1.5.x.

+41
java compiler-construction arrays literals hex
Aug 18 '10 at 19:43
source share
4 answers

As another answer already said, a byte is a signed type in Java. The range is from -128 to 127 inclusive. So 0xff is -0x01. You can use 0xff instead of -0x01 if you add manual mode:

 byte[] rawbytes={0xa, 0x2, (byte) 0xff}; 
+38
Aug 18 '10 at 19:51
source share

There is another possibility by declaring a helper function with variable arguments. This may be preferable if you need to declare arrays with multiple bytes.

Code example

 public static byte[] toBytes(int... ints) { // helper function byte[] result = new byte[ints.length]; for (int i = 0; i < ints.length; i++) { result[i] = (byte) ints[i]; } return result; } public static void main(String... args) { byte[] rawbytes = toBytes(0xff, 0xfe); // using the helper for (int i = 0; i < rawbytes.length; i++) { System.out.println(rawbytes[i]); // show it works } } 
+11
Jul 16 2018-12-12T00:
source share

byte signed and 0xff = 255 too big. Allowed range (-128 .. 127).

Code example:

 public static void main(String[] args) { byte b = (byte) 0xff; // = -1 int i = b; // = -1 int j = b & 0xff; // = 255 System.out.printf("b=%s, i=%s, j=%s", b,i,j); } 
+7
Aug 18 '10 at 19:44
source share

"0xFF" is an int literal for the decimal value 255, which is not represented as a byte.

Now you need to pass it to byte to tell the compiler that you really mean -1, for example:

 byte[] rawbytes = { 0xA, 0x2, (byte) 0xFF }; 

It was suggested to add a new byte literal syntax ( y or y suffix) in Java 7. Then you could write:

 byte[] rawbytes = { 0xA, 0x2, 0xFFy }; 

However, this proposal was not included in the "omnibus proposal for improving integral literals", so we were stuck on the sheet forever.

+7
Aug 18 '10 at 19:47
source share



All Articles