how can I assign -1 as Hex Literal to byte type var?

Waez Ali
Greenhorn
Posts: 22
hi,
I want to assigne -128 to the byte type ,I can do it in the following ways

byte b1 = -128; //int but within byte range
byte b2 = -0x80; // hexadecimal for -128
System.out.println("b1 ="+b1+" b2 ="+b2);
output
-128 -128

Now I want to assigne -1 in the same way

byte b1 = -1; //int within byte range
byte b2 = -0xff; // hexadecimal of -1
System.out.println("b1 ="+b1+" b2 ="+b2);

But I m getting error at line
--> byte b2 = -0xff ;
Possible loss of precision...

But If I do explicit cast,It will assigne +1 to b2

How Can I assign -1 in hex to byte ?

Thanks ...
[ January 27, 2005: Message edited by: Waez Ali ]

Peter Chase
Ranch Hand
Posts: 1970
Hex literals are int. Therefore, your literal 0xff is really 0x000000ff, which is a positive int. When you apply unary "-" operator to that, you get a negative int (0xffffff01, I think). That negative int is not in byte range.

Waez Ali
Greenhorn
Posts: 22
Hi peter,

Does that mean i can not assign -1 or -2 as hex literals to byte var?
I am still not clear bkz it allows other -ve numbers like -121 -128 etc.

thanks.

Peter Chase
Ranch Hand
Posts: 1970
Hopefully, this clears it up: -

Murali Krishnamoorthy
Greenhorn
Posts: 1
hi
It looks like -0xff is a hexadecimal value for - 255.

murali

Waez Ali
Greenhorn
Posts: 22
Hi Peter,
Thanks for such a good explanation.
You are just great.

Thak you once again.