Why can not use hex Int in kotlin method intArrayOf?


I found a strange problem in Kotlin.

I can assign a hexadecimal integer to an Int variable, just like:

private val a = 0xFFFF0000    //works good

but I can't use this hex integer in intArrayOf:

private val array: IntArray = intArrayOf(0xFFFF0000)

IDE prompts: the integer literal does not conform to the expected type Int. enter image description here

Does anyone know why? and is there anyway to use 0xFFFF0000 in intArrayof?

asked on Stack Overflow Nov 12, 2019 by L. Swifter

2 Answers


While 0x7FFF_FFFF is of typ Int, hex literals starting from 0x8000_0000 are of type Long.

You need 32 bit to store 0x8000_0000. While Int is signed, the value is (the least one, that is) too big to be stored in an Int.

You can use negative hex literals though

val a: IntArray = intArrayOf(-0x1_0000)

If you are on the JVM, you can check with

a.forEach { println(Integer.toHexString(it)) }
assert(0x7FFF_FFFF == Integer.MAX_VALUE)
assert(-0x8000_0000 == Integer.MIN_VALUE)
answered on Stack Overflow Nov 12, 2019 by Frank Neblung

because 0xFFFF0000 is Long Type,

You can use private val array: IntArray = intArrayOf(0xFFFF0000.toInt())

to change type from Long to Int

or declare LongArray type

like private val array: LongArray = longArrayOf(0xFFFF0000)

answered on Stack Overflow Nov 12, 2019 by GuanHongHuang

User contributions licensed under CC BY-SA 3.0