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

monojohnny picture monojohnny · Aug 18, 2010 · Viewed 49.3k times · Source

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.

Answer

Hendrik Brummermann picture Hendrik Brummermann · Aug 18, 2010

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