Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Kotlin support unsigned integers?

I came across a situation just recently in which an unsigned integer would have been really useful (e.g. any negative value would not make sense etc.). Surprisingly, I discovered that Kotlin does not support unsigned integers - and there doesn't appear to be anything else out there about why (even though I've looked).

Am I missing something?

like image 437
starbeamrainbowlabs Avatar asked May 07 '18 19:05

starbeamrainbowlabs


People also ask

Why there is no unsigned int in Java?

The Java language specification requires its signed integers to be represented in two's complement format. Because of this, many basic operations are exactly the same whether the integer type is signed or unsigned.

Should you use unsigned ints?

The Google C++ style guide recommends avoiding unsigned integers except in situations that definitely require it (for example: file formats often store sizes in uint32_t or uint64_t -- no point in wasting a signedness bit that will never be used).

What is ULong in Kotlin?

The kotlin. UInt is an unsigned 32-bit integer (0 to 2^32 – 1) The kotlin. ULong is an unsigned 64-bit integer (0 to 2^64 -1)

Is there an unsigned int in Java?

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.


1 Answers

Unsigned counterparts of Byte, Short, Int and Long do exist in Beta since Kotlin 1.3 and are stable as of Kotlin 1.5:

From the docs:

kotlin.UByte: an unsigned 8-bit integer, ranges from 0 to 255
kotlin.UShort: an unsigned 16-bit integer, ranges from 0 to 65535
kotlin.UInt: an unsigned 32-bit integer, ranges from 0 to 2^32 - 1
kotlin.ULong: an unsigned 64-bit integer, ranges from 0 to 2^64 - 1

Usage

// You can define unsigned types using literal suffixes
val uint = 42u 

// You can convert signed types to unsigned and vice versa via stdlib extensions:
val int = uint.toInt()
val uint = int.toUInt()
like image 78
Willi Mentzel Avatar answered Oct 28 '22 08:10

Willi Mentzel