ChatGPT解决这个技术问题 Extra ChatGPT

Declaring an unsigned int in Java

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.

There are no unsigned types in Java.
This post might help you stackoverflow.com/a/4449161/778687
Doesn't seem to be a way AFAICT. Related: stackoverflow.com/questions/430346/…
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 >>.

A
Aleksandr Dubinsky

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.


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.
Z
Zsolt Safrany

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, that it is important that the hex literal is a long literal, not an int literal - hence the 'L' at the end.


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)
L
Lukas Eder

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)


This sounds very convenient! Thanks for mentioning. :)
r
randers

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

UnsignedInteger

UnsignedLong

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.


M
Molossus Spondee

Use char for 16 bit unsigned integers.


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)
M
Matthias Ronge

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


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;?
C
Community

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.


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]
A
Artem

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

R
Romulo

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);
                    }

P
Peter Mortensen

You can use the Math.abs(number) function. It returns a positive number.


nitpick: not if you pass in MIN_VALUE
@kyo722 I can't imagine that this will return a positive value in the range of unsigned primitives.
nitpick #2: not if you pass in 0