How to convert a Long
/ULong
representing an unsigned long to an unsigned hexadecimal string with padding zeros (a 16-digit hexadecimal string)?
I am looking for a simple and neat solution in Kotlin or Java.
How to convert a Long
/ULong
representing an unsigned long to an unsigned hexadecimal string with padding zeros (a 16-digit hexadecimal string)?
I am looking for a simple and neat solution in Kotlin or Java.
val mutableList = listOf(121212L, 121212121212L,-1L)
mutableList.forEach {
println(it.toULong().toString(16).padStart(16, '0'))
}
it gives
000000000001d97c
0000001c38ce307c
ffffffffffffffff
Edited: Credit to Ilya in the comment for the missing toULong part.
I have found the solution using x
/X
in String.format()
:
fun Long.to16DigitUnsignedLowercaseHexString() =
"%016x".format(this)
fun Long.to16DigitUnsignedUppercaseHexString() =
"%016X".format(this)
I have tested that it works for boundary values 0L
, 1L
, Long.MAX_VALUE
, -1L
, and Long.MIN_VALUE
, so there should be no problems.
A similar question is asked in java - How can I pad an integer with zeros on the left? - Stack Overflow. When looking at this for the first time, I didn't expect it to work because I thought that x
/X
is for signed hexadecimal formatting. It turned out I was wrong and x
/X
is exactly for unsigned hexadecimal formatting.