3 ms·
Other than sign-extension on right shift, I can't think of a bitwise operator that has a different implementation between signed/unsigned. What scenarios are y
by recursive 5y ago
Other than sign-extension on right shift, I can't think of a bitwise operator that has a different implementation between signed/unsigned. What scenarios are you thinking of?
- xxs 5y agoreading and processing bytes mostly. Many people get confused due to the need of bitwise and, yet even if that would be removed I can't quite see the intrinsic benefits, given how difficult would be having another primitive type.
- recursive 5y agoSo, when processing bytes, can you name an operation where the existence of an unsigned type would even make a difference? I'm still not seeing it.
- eMSF 5y agoJava bytes are signed. They aren't useful when working with unsigned 8-bit values (say, a scaling factor or an index in whatever binary format you are trying to parse). You need a larger integer type, and indeed that bitwise and operation to get the range of values you need.
- xxs 5y agojava virtually has only 2 integer types int and long, or 4 and 8 bytes one. So all operations are converted to int (or long) 1st, even when they involve byte/short, etc. Imagine you try to combine a 4bytes (from an array) into a single int. If you just bitwise OR and shift left, e.g. something like (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3] it won't work, you need ((b[1] & 0ff) << 16), etc. The byte values greater than 127 would have the sign bit set (and all other higher bits to make the 2complimentary form) That part is somewhat alleviated by wrapping byte arrays into ByteBuffers that would the right thing, or even better using only ByteBuffers (preferably the direct version of them when reading from input/output)
- rzzzt 5y agoJava has both >> and >>> operators for sign-extending and zero-extending right shift, respectively.