Original Post
🔒 Locked
quick java question
Advertisement
in general, no. technically, yes. read thedefinition of unsigned in java.
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:
Of course, optimization (according to the specific way in which you are using the variables) is left as an exercise ;)
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):
so why does makes java decide its positive? is it the typecast to integer or what is it?
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------------- 10010100so why does makes java decide its positive? is it the typecast to integer or what is it?
Topic Locked
This topic has been locked by a moderator. New replies are not allowed.
Sign in to reply to this topic.
Advertisement