Literal Syntax For byte[] arrays using Hex notation..?

JavaArraysCompiler ConstructionHexLiterals

Java Problem Overview


The compiler seems to be ok with this (single digit hex values only):

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

But not this:

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

I get a "Possible Loss of Precision found : int required : byte" error?

What am I doing wrong - or are single digit hex numbers a special case ?

Java 1.5.x.

Java Solutions


Solution 1 - Java

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

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

Solution 2 - Java

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

Example code

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
	}
}

Solution 3 - Java

"0xFF" is an int literal for the decimal value 255, which isn't representable as a byte.

For now, you'll need to cast it to a byte to tell the compiler you really mean -1, like this:

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

It was proposed to add a new byte literal syntax (y or Y suffix) to Java 7. Then you would have been able to write:

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

However, this proposal was not included in the "omnibus proposal for improved integral literals," so we be stuck with the cast forever.

Solution 4 - Java

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

Example code:

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);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmonojohnnyView Question on Stackoverflow
Solution 1 - JavaHendrik BrummermannView Answer on Stackoverflow
Solution 2 - JavaEero AaltonenView Answer on Stackoverflow
Solution 3 - JavaericksonView Answer on Stackoverflow
Solution 4 - JavaAndreas DolkView Answer on Stackoverflow