Reputation: 2821
With Integer.toString(1234567, 16).toUpperCase() // output: 12D68
could help to convert an Int
to Hex string.
How to do the same with Long?
Long.toString(13690566117625, 16).toUpperCase() // but this will report error
Upvotes: 15
Views: 20623
Reputation: 149538
You're looking for RichLong.toHexString
:
scala> 13690566117625L.toHexString
res0: String = c73955488f9
And the uppercase variant:
scala> 13690566117625L.toHexString.toUpperCase
res1: String = C73955488F9
This also available for Int
via RichInt.toHexString
:
scala> 42.toHexString
res4: String = 2a
Upvotes: 23
Reputation: 2103
The benefit of using Scala is the ability to use Java libraries.
So, you could implement :
import scala.util.Try
val longToHexString = Try(java.lang.Long.toString(13690566117625, 16)) // handle exceptions if any
Upvotes: 0
Reputation: 3376
I've found f"0x$int_val%08X"
or f"0x$long_val%16X"
to work great when you want to align a value with leading zeros.
scala> val i = 1
i: Int = 1
scala> f"0x$i%08X"
res1: String = 0x00000001
scala> val i = -1
i: Int = -1
scala> f"0x$i%08X"
res2: String = 0xFFFFFFFF
scala> val i = -1L
i: Long = -1
scala> f"0x$i%16X"
res3: String = 0xFFFFFFFFFFFFFFFF
Upvotes: 5
Reputation: 51271
val bigNum: Long = 13690566117625L
val bigHex: String = f"$bigNum%X"
Use %X
to get uppercase hex letters and %x
if you want lowercase.
Upvotes: 15
Reputation: 206816
You have several errors. First of all, the number 13690566117625
is too large to fit in an int
so you need to add an L
prefix to indicate that it's a long
literal. Second, Long
does not have a toString
method that takes a radix (unlike Integer
).
Solution:
val x = 13690566117625L
x.toHexString.toUpperCase
Upvotes: 3