views:

106

answers:

3

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.

+6  A: 

byte is signed and 0xff = 255 is to 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);
}
Andreas_D
+2  A: 

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

Java 7 adds a new byte literal syntax (y or Y suffix) to avoid this problem. You'll be able to write:

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

Hmm, after more reading, it's not clear if the "omnibus proposal for improved integral literals" includes this proposal or not. Might have to stick with the cast forever.

erickson
+1  A: 

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