429

Is there a way to declare an unsigned int in Java?

Or the question may be framed as this as well: What is the Java equivalent of unsigned?

Just to tell you the context I was looking at Java's implementation of String.hashcode(). I wanted to test the possibility of collision if the integer were 32 unsigned int.

10
  • 10
    There are no unsigned types in Java. Commented Mar 24, 2012 at 18:11
  • 1
    This post might help you stackoverflow.com/a/4449161/778687 Commented Mar 24, 2012 at 18:11
  • 2
    Doesn't seem to be a way AFAICT. Related: stackoverflow.com/questions/430346/… Commented Mar 24, 2012 at 18:13
  • 15
    It depends on the purpose you're trying to achieve. For most purposes, all integers in Java are signed. However, you can treat a signed integer as unsigned in one specific case: you can shift right without sign extending by using >>> operator instead of >>. Commented Mar 24, 2012 at 18:19
  • 2
    See also How to use the unsigned Integer in Java 8 and Java 9? Commented Mar 3, 2018 at 19:00

10 Answers 10

419

Java does not have a datatype for unsigned integers.

You can define a long instead of an int if you need to store large values.

You can also use a signed integer as if it were unsigned. The benefit of two's complement representation is that most operations (such as addition, subtraction, multiplication, and left shift) are identical on a binary level for signed and unsigned integers. A few operations (division, right shift, comparison, and casting), however, are different. As of Java SE 8, new methods in the Integer class allow you to fully use the int data type to perform unsigned arithmetic:

In Java SE 8 and later, you can use the int data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 2^32-1. Use the Integer class to use int data type as an unsigned integer. Static methods like compareUnsigned, divideUnsigned etc have been added to the Integer class to support the arithmetic operations for unsigned integers.

Note that int variables are still signed when declared but unsigned arithmetic is now possible by using those methods in the Integer class.

Sign up to request clarification or add additional context in comments.

12 Comments

To be fair, for many projects the technical requirements aren't that strict and you can indeed afford to "waste" memory like that.
I know, I also understand the original purpose of Java. But for example Smartphones do not dispose with extra memory. And they usually use Java, as far as I know. But well, I don't want to start a war between Java programers and the others.
To me this isn't just a case of wasting money. When you work on a bit level, unsigned is simply easier to work with
As of Java 8, this is no longer true. In Java SE 8 and later, you can use the int data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 2^32-1. - see docs.oracle.com/javase/tutorial/java/nutsandbolts/… and docs.oracle.com/javase/8/docs/api/java/lang/Integer.html
@7SpecialGems: I have updated the answer to include that information. That being said, it's not possible to declare unsigned integers or exclude negative values, it's only possible to use an int as if it were unsigned by using various methods.
|
91

Whether a value in an int is signed or unsigned depends on how the bits are interpreted - Java interprets bits as a signed value (it doesn't have unsigned primitives).

If you have an int that you want to interpret as an unsigned value (e.g. you read an int from a DataInputStream that you know should be interpreted as an unsigned value) then you can do the following trick.

int fourBytesIJustRead = someObject.getInt();
long unsignedValue = fourBytesIJustRead & 0xffffffffL;

Note: it is important that the hex literal is a long literal, not an int literal - hence the 'L' at the end.

6 Comments

For me this is the best answer... My data comes from an NFC card UID, which can have 4 or 8 bytes... In the case of 4 bytes I needed to cast it to an unsigned int, and I couldn't use ByteBuffer.getLong because it was not 64-bit data. Thanks.
Why does it need to be a long. Can't you just do 0xFFFFFF and keep the int?
@Displee Just think that through. If you AND an int with 32 bits of 1s, why would Java interpret your new variable any differently than the original value? That‘s 8 F‘s, not 6, btw, because 0xF=1111 and you need 32 of those 1s)
Why don't you directly do long unsignedValue = someObject.getInt();? What is the benefits of "ANDing" that int value with 0xFFFFFFFFL?
@MohammadKholghi casting an int to long will sign-extend (i.e., if the int would be negative, the long will be negative). in effect this means all upper bits of the long get set to 1. if you mask against 32 bits, you will get only those 32 bits, so it will always be positive. the "L" at the end makes it a long literal rather than an int
|
28

We needed unsigned numbers to model MySQL's unsigned TINYINT, SMALLINT, INT, BIGINT in jOOQ, which is why we have created jOOU, a minimalistic library offering wrapper types for unsigned integer numbers in Java. Example:

import static org.joou.Unsigned.*;

// and then...
UByte    b = ubyte(1);
UShort   s = ushort(1);
UInteger i = uint(1);
ULong    l = ulong(1);

All of these types extend java.lang.Number and can be converted into higher-order primitive types and BigInteger. Hope this helps.

(Disclaimer: I work for the company behind these libraries)

Comments

10

For unsigned numbers you can use these classes from Guava library:

They support various operations:

  • plus
  • minus
  • times
  • mod
  • dividedBy

The thing that seems missing at the moment are byte shift operators. If you need those you can use BigInteger from Java.

Comments

6

There are good answers here, but I don’t see any demonstrations of bitwise operations. Like Visser (the currently accepted answer) says, Java signs integers by default (Java 8 has unsigned integers, but I have never used them). Without further ado, let‘s do it...

RFC 868 Example

What happens if you need to write an unsigned integer to IO? Practical example is when you want to output the time according to RFC 868. This requires a 32-bit, big-endian, unsigned integer that encodes the number of seconds since 12:00 A.M. January 1, 1900. How would you encode this?

Make your own unsigned 32-bit integer like this:

Declare a byte array of 4 bytes (32 bits)

Byte my32BitUnsignedInteger[] = new Byte[4] // represents the time (s)

This initializes the array, see Are byte arrays initialised to zero in Java?. Now you have to fill each byte in the array with information in the big-endian order (or little-endian if you want to wreck havoc). Assuming you have a long containing the time (long integers are 64 bits long in Java) called secondsSince1900 (Which only utilizes the first 32 bits worth, and you‘ve handled the fact that Date references 12:00 A.M. January 1, 1970), then you can use the logical AND to extract bits from it and shift those bits into positions (digits) that will not be ignored when coersed into a Byte, and in big-endian order.

my32BitUnsignedInteger[0] = (byte) ((secondsSince1900 & 0x00000000FF000000L) >> 24); // first byte of array contains highest significant bits, then shift these extracted FF bits to first two positions in preparation for coersion to Byte (which only adopts the first 8 bits)
my32BitUnsignedInteger[1] = (byte) ((secondsSince1900 & 0x0000000000FF0000L) >> 16);
my32BitUnsignedInteger[2] = (byte) ((secondsSince1900 & 0x000000000000FF00L) >> 8);
my32BitUnsignedInteger[3] = (byte) ((secondsSince1900 & 0x00000000000000FFL); // no shift needed

Our my32BitUnsignedInteger is now equivalent to an unsigned 32-bit, big-endian integer that adheres to the RCF 868 standard. Yes, the long datatype is signed, but we ignored that fact, because we assumed that the secondsSince1900 only used the lower 32 bits). Because of coersing the long into a byte, all bits higher than 2^7 (first two digits in hex) will be ignored.

Source referenced: Java Network Programming, 4th Edition.

4 Comments

Is this the java implementation of a new array? Byte my32BitUnsignedInteger[] = new Byte[4] // represents the time (s) This is just a little 'huh' for me. I remember you were supposed to do this Byte[] my32BitUnsignedInteger = new Byte[4] Correct me if I am wrong.
@Yolomep Yes, it is Java syntax. Appending brackets to the type or name is fine.
Wow. I didn't know that. I thought that kind of array declaration was only for c++.
Your Bytes are the boxed classes. You want to use byte[] array = new byte[4]
5

Perhaps this is what you meant?

long getUnsigned(int signed) {
    return signed >= 0 ? signed : 2 * (long) Integer.MAX_VALUE + 2 + signed;
}
  • getUnsigned(0) → 0
  • getUnsigned(1) → 1
  • getUnsigned(Integer.MAX_VALUE) → 2147483647
  • getUnsigned(Integer.MIN_VALUE) → 2147483648
  • getUnsigned(Integer.MIN_VALUE + 1) → 2147483649

2 Comments

You're sacrificing a zillionth of a second of performance time for lazy typing with ternary operators instead of if statements. Not good. (kidding)
Do you really think, 2 * (long) Integer.MAX_VALUE + 2 is easier to understand than 0x1_0000_0000L? In that regard, why not simply return signed & 0xFFFF_FFFFL;?
5

Use char for 16 bit unsigned integers.

1 Comment

Char are not 32bit unsigned int but char is a good answer for memory gain. this link : stackoverflow.com/questions/1841461/unsigned-short-in-java (from jqr above)
2

It seems that you can handle the signing problem by doing a "logical AND" on the values before you use them:

Example (Value of byte[] header[0] is 0x86 ):

System.out.println("Integer "+(int)header[0]+" = "+((int)header[0]&0xff));

Result:

Integer -122 = 134

Comments

1

Just made this piece of code, wich converts "this.altura" from negative to positive number. Hope this helps someone in need

       if(this.altura < 0){    

                        String aux = Integer.toString(this.altura);
                        char aux2[] = aux.toCharArray();
                        aux = "";
                        for(int con = 1; con < aux2.length; con++){
                            aux += aux2[con];
                        }
                        this.altura = Integer.parseInt(aux);
                        System.out.println("New Value: " + this.altura);
                    }

Comments

1

Many people have said it, as of java-8, it is possible to work with unsigned types, but its not possible to declare those. I had to do a bit of drawing to understand how the implementation works for :

public static int compareUnsigned(int x, int y) {
   return compare(x + MIN_VALUE, y + MIN_VALUE);
}

So will write it in here, may be someone finds it useful.

                                                 MAX_VALUE in unsigned format 
                                                      (2 pow 64) - 1
                                                           ---
                                                          |   |
(2 pow 63) - 1                                            |   |
(MAX_VALUE)                                               |   |
   ---                                                     ---    <-- 2 pow 63
  |   |                                                   |   |
  |   |                                                   |   |
  |   |                                                   |   |
   ---  <-- 0 (zero)   +   Integer.MIN_VALUE =             ---                                
  |   |                                          MIN_VALUE in unsigned format            
  |   |                                                  (zero)
  |   |
   ---
(MIN_VALUE)
- (2 pow 63)

If we take Integer.MIN_VALUE and think about it in terms of unsigned, then it is equal to 2 pow 63. So if we add that value to any other long value, we will shift it "upwards" by that "2 pow 63".

To take it to the extreme, the lowest possible value in the signed world would be : -(2 pow 63), add Integer.MIN_VALUE and we get zero.

The highest possible value in signed world is (2 pow 63) - 1, add Integer.MIN_VALUE and we get (2 pow 64) - 1.

That range : zero to (2 pow 64) - 1 is still 64 bits, like any long, thus the comparison can happen.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.