views:

334

answers:

5

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.

+7  A: 

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.

Jon Skeet
You sure that it actually saves you memory? I don't think it does--I think Java uses whatever your word size is to hold a byte (Except in arrays, which it will pack). In either case, you're taking a little speed hit not to use ints though.
Bill K
+1  A: 

Nope, you can't change that. If you need something larger than 127 choose something larger than a byte.

Bart Kiers
+3  A: 

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...
   }
Pierre
That is possible. But if I want a unsigned var, it's for the memory-size. If not, I can use an int.
Martijn Courteaux
erickson
Pierre
+2  A: 

You can mostly use signed numbers as if they were unsigned. Most operations stay the same, some need to be modified. See this post.

starblue
+1  A: 

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.

Bill K
+1 for explaining why using an unsigned would not achieve any space saving ... which is apparently what the OP is trying to do.
Stephen C
@Stephen: concerns about space are certainly about arrays unless OP is utterly clueless. Anyway, what type would you use for a large array of byte-size samples? I suppose you can use bytes and just mask them with 255, but this issue is a major flaw in Java.
R..