Search code examples
javakotlinformattingnumber-formattinglong-integer

Convert a Long/ULong to an unsigned hexadecimal string with padding zeros


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.


Solution

  • 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.