Kotlin中的无符号数据类型

发布时间 2023-05-24 15:43:11作者: jqc

无符号数据类型

Kotlin支持了几种常见的无符号整型,如下表所示:

数据类型 数据大小 取值范围
UByte 1字节 0 ~ 255
UShort 2字节 0 ~ 65535
UInt 4字节 0~ 2^32-1
ULong 8字节 0 ~ 2^64-1

除此之外,还支持了对应无符号整型的数组类型:

  • UByteArray
  • UShortArray
  • UIntArray
  • ULongArray

使用无符号整型的字面值直接在数字后面加上 u 即可:

val b: UByte = 1u
val s: UShort = 1u
val l: ULong = 1u

实现原理

Kotlin的无符号整型并不是真的新增了一些数据类型,而是一个语法糖
以UShort为例,UShort实际底层是用Short类型来存储数据,将Short类型的负值区间 [-128, -1] 映射到 [128, 255]即可。
查看UShort的与源码可以发现UShort.MAX_VALUE即对应Short类型的-1

public value class UShort internal constructor(internal val data: Short) {

	companion object {
   		public const val MIN_VALUE: UShort = UShort(0)
   		public const val MAX_VALUE: UShort = UShort(-1)
   	}
}

而对于UShort类型的运算和展示,会先转成取值范围更大一级的数据类型再进行运算和展示

public inline operator fun plus(other: UShort): UInt = this.toUInt().plus(other.toUInt())
public inline operator fun minus(other: UShort): UInt = this.toUInt().minus(other.toUInt())
public override fun toString(): String = toInt().toString()