00 Votes

Java: Declare unsigned Integer

Question by Guest | 2016-08-04 at 23:30

In all programming languages I know, you are able to declare and use so-called "unsigned integers" which are numbers without sign. The advantage is, that you can store larger (twice as large) numbers at the same bit length because the negative number range is omitted (which is in many cases not used anyway).

Usually, the corresponding types are called uint, word or unsigned int in SQL. Now, I have dealed with Java for the first time of my life and somehow, I could not find any unsigned types in this language. Can someone tell me for what I should use? How are the unsigned types in Java called and how is the unsigned concept implemented there?

ReplyPositiveNegativeDateVotes
0Best Answer0 Votes

First, I have also only barely believed it, but there are indeed no unsigned types available in Java. You can only use the usual integer types such as int (32 Bit), long (64 Bit), byte (8 Bit) or short (16 Bit) that are all signed.

That is only the data type char (8 bit, value range from 0 to 65535) available in Java that is quasi "unsigned". Unfortunately, there is no equivalent for larger types.

However, there was a little change since Java 8. Admittedly, the integer types are still signed in Java 8 and there is also no possibility to explicitly declare an integer as unsigned, but there are some new methods available that are designed in a way, that they can internally handle "unsigned types":

int i = Integer.parseUnsignedInt("4294967295");
string si = Integer.toUnsignedString(i);
System.out.println(i);   // -1
System.out.println(si);  // 4294967295

long l = Long.parseUnsignedLong("18446744073709551615");
string sl = Long.toUnsignedString(l);
System.out.println(l);   // -1
System.out.println(sl);  // 18446744073709551615

This example shows how you can use the new methods and where there limits are.
2016-08-05 at 21:20

ReplyPositive Negative
11 Vote

If it is very important for you to use unsigned integers in Java, you can also use an external library such as Guava.

This library contains (for example) the following classes:

Those classes are publishing functions such as .plus(), .minus(), .times(), .dividedBy() or .mod() so that you can calculate with them.

You can find some introduction hier.
2016-08-06 at 21:16

ReplyPositive Negative
Reply

Related Topics

MySQL: Integer Types

Info | 0 Comments

Delphi: System-Wide HotKey

Tutorial | 1 Comment

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.