Discussions
Categories
Groups
Advertisement
Child Item
Home
Topics
Technology & Internet
Software & Web Development
Development
java bits and bytes problem...
[Deleted User]
Hey all,
My program is working fine except for one little error.
I am getting the high and low byte of a short type in java.
The high byte seems to work out ( shift 8 bits then AND with mask 0xFF) but the low byte is screwing up when a decimal number such as 1000 is passed.
the binary for 1000 is
00000011 11101000
and the low byte is
1110 1000
This, in the program , keeps coming up with -24 and a messed up hex value. Other values work ok, just when the low byte begins with 1, then problems arise.
Does anyone have any indication as to what the problem may be?
I'm thinking that's it's some unsigned/signed problem with the byte and short data types but that's just me.
Help would be really appreciated,
thanks
Find more posts tagged with
Quick Links
All Categories
Recent Posts
Activity
Unanswered
Groups
Best Of
Advertisement
Advertisement
Comments
seamus
IIRC, all numbers in java are signed by default.
Maybe try specifying it as
unsigned short myShort = 1000;
And that may work...but I'm a bit rusty on that
Zab
Actually, sun decided not to include the 'unsigned' keyword, or the concept in Java. Well, the char type is unsigned, which is kind of handy at times..
Anyway, as seamus noted, you are indeed having a problem with the number being interpreted as signed. My guess would be that you are casting it as a byte somewhere along the line. If you have to do this, then you can mask it off again when you want to print it out. Just remember that if you are basing any logic on it, java will presume it is a signed number ( between -128 and 127 ).
Zab.
[Deleted User]
Yeah I was using it as a byte somewhere, it's awkward, the hexa decimal now comes out alright, but the decimal still comes out as a minus number.
frustrating, I think for the moment i'll leave it printing out the hex value, head wrecking at the moment.
thanks for the help all
Zab
As I was saying, if it is purely for display purposes, you could just write something like
byte b = -33;
System.out.println( b & 0xff );
Which will print out b as an unsigned value ( 223 in this case ).
Zab.