Skip to main content
gamedev.net
🔒 Locked

quick java question

Started by UeberBobo Oct 31, 2004 at 6:20 PM 6 replies 1.3k views
Original Post
UeberBobo
UeberBobo
my book on the subject mentions nothing about it, so i wonder, can i make an unsigned variable in java like in c++, and if so, how? thanks
//---------//Ueberbobo//***
UeberBobo
UeberBobo
hmm, so would an int would take less space in memory if i masked it off like that? could you explain what happens here a bit further?
//---------//Ueberbobo//***
TarinX
TarinX
No, an int will use the same amount of memory regardless of the operation you are doing on it.
UeberBobo
UeberBobo
but then, aint there little point in doing this? i might as well use the whole integer then, instead of masking it off to simulate an unsigned 8-bit, if theres no gain in memory use, right?
//---------//Ueberbobo//***
Zahlman
Zahlman
In some cases it will be possible to keep the value stored in a normal-sized variable (as signed; so a value in the top half of the range will instead be stored as a negative value) and just do the masking when you need to do a calculation - then store the result back if needed. Example:

byte numberOfEggs = (byte)144; // actually -112// ...// Tell the user how many dozens of eggs there are.System.out.println("You have " + (numberOfEggs & 255) / 12 + "dozen eggs.");// ...// Oh noes! Teh haxorz haev st0len half the eggs!!!11numberOfEggs = (byte)((numberOfEggs & 255) / 2);// The byte cast is necessary even though the value is < 128,// because Java promotes everything to an int when evaluating// the arithmetic expression.


Of course, optimization (according to the specific way in which you are using the variables) is left as an exercise ;)
UeberBobo
UeberBobo
zahlman: thanks that cool. could you explain how it works though?

to me it feels like (byte & 255) would just stay the same as it is...
say we take the number -236 (or whatever):
    10010100 &  11111111-------------    10010100


so why does makes java decide its positive? is it the typecast to integer or what is it?
//---------//Ueberbobo//***
Zahlman
Zahlman
As I alluded to, all the intermediate calculations are done in integers. So if you need to use unsigned ints, you'll have to add some (long) casts; and if you need to use unsigned longs, you're SOL :)

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.