quick java question

Started by
6 comments, last by Zahlman 19 years, 5 months ago
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//*********
Advertisement
in general, no. technically, yes. read thedefinition of unsigned in java.
- stormrunner
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//*********
No, an int will use the same amount of memory regardless of the operation you are doing on it.
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//*********
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 ;)
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//*********
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 :)

This topic is closed to new replies.

Advertisement