15

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

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
mCY
  • 2,731
  • 7
  • 25
  • 43
  • What error did you get? What if you used "`13690566117625L`" with an L at the end? – kennytm Sep 15 '16 at 07:55
  • @kennytm, `Long.toString(13690566117625L, 16).toUpperCase()`, it would say `error: too many arguments for method toString: ()String` – mCY Sep 15 '16 at 07:59

5 Answers5

23

You're looking for RichLong.toHexString:

scala> 13690566117625L.toHexString
res0: String = c73955488f9

And the uppercase variant:

scala> 13690566117625L.toHexString.toUpperCase
res1: String = C73955488F9

Edit

This also available for Int via RichInt.toHexString:

scala> 42.toHexString
res4: String = 2a
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
15
val bigNum: Long   = 13690566117625L
val bigHex: String = f"$bigNum%X"

Use %X to get uppercase hex letters and %x if you want lowercase.

jwvh
  • 50,871
  • 7
  • 38
  • 64
  • Also you can do padding e.g. with zeros to a length of 16 like this: `f"$bigNum%016X"` – amoebe Dec 10 '17 at 09:22
  • 2
    Yes indeed. You can also add the standard hex designation to the formatted output: `f"$myNum%#x"` results in `0x1c4`. A concise means to express values in many different hex formats. – jwvh Dec 11 '17 at 05:40
5

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
Martin Tapp
  • 3,106
  • 3
  • 32
  • 39
3

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
Jesper
  • 202,709
  • 46
  • 318
  • 350
0

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

ForeverLearner
  • 1,901
  • 2
  • 28
  • 51