Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

java bits and bytes problem...

Options
  • 03-02-2003 4:07pm
    #1
    Posts: 0


    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


Comments

  • Registered Users Posts: 68,317 ✭✭✭✭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 :)


  • Registered Users Posts: 1,931 ✭✭✭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.


  • Posts: 0 [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 :)


  • Registered Users Posts: 1,931 ✭✭✭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.


Advertisement