Hello,
Is there a way in Java to use Unsigned numbers like in (My)SQL?
For example: I want to use an 8-bit variable (byte) with a range
like: 0
-> 256
; instead of -128
-> 127
.
Hello,
Is there a way in Java to use Unsigned numbers like in (My)SQL?
For example: I want to use an 8-bit variable (byte) with a range
like: 0
-> 256
; instead of -128
-> 127
.
No, Java doesn't have any unsigned primitive types apart from char
(which has values 0-65535, effectively). It's a pain (particularly for byte
), but that's the way it is.
Usually you either stick with the same size, and overflow into negatives for the "high" numbers, or use the wider type (e.g. short
for byte
) and cope with the extra memory requirements.
Nope, you can't change that. If you need something larger than 127 choose something larger than a byte.
You can use a class to simulate an unsigned number. For example
public class UInt8 implements Comparable<UInt8>,Serializable
{
public static final short MAX_VALUE=255;
public static final short MIN_VALUE=0;
private short storage;//internal storage in a int 16
public UInt8(short value)
{
if(value<MIN_VALUE || value>MAX_VALUE) throw new IllegalArgumentException();
this.storage=value;
}
public byte toByte()
{
//play with the shift operator ! <<
}
//etc...
}
Internally, you shouldn't be using the smaller values--just use int. As I understand it, using smaller units does nothing but slow things down. It doesn't save memory because internally Java uses the system's word size for all storage (it won't pack words).
However if you use a smaller size storage unit, it has to mask them or range check or something for every operation.
ever notice that char (any operation) char yields an int? They just really don't expect you to use these other types.
The exceptions are arrays (which I believe will get packed) and I/O where you might find using a smaller type useful... but masking will work as well.