This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Java in General and the fly likes how can I assign -1 as Hex Literal to byte type var? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "how can I assign -1 as Hex Literal to byte type var?" Watch "how can I assign -1 as Hex Literal to byte type var?" New topic
Author

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

Waez Ali
Greenhorn

Joined: Jan 10, 2005
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 ?
Please explain me this concept.

Thanks ...
[ January 27, 2005: Message edited by: Waez Ali ]
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
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.


Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Waez Ali
Greenhorn

Joined: Jan 10, 2005
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.
Can you please elaborate it.

thanks.
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
Hopefully, this clears it up: -

Murali Krishnamoorthy
Greenhorn

Joined: Jan 27, 2005
Posts: 1
hi
It looks like -0xff is a hexadecimal value for - 255.

murali
Waez Ali
Greenhorn

Joined: Jan 10, 2005
Posts: 22
Hi Peter,
Thanks for such a good explanation.
You are just great.

Thak you once again.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: how can I assign -1 as Hex Literal to byte type var?