30

I am starting to work in Kotlin and I need to parse a hex String to a long, which in java can be done with

Long.parseLong("ED05265A", 16); 

I can not find anything this in Kotlin, although I can find

val i = "2".toLong()

This is not what I am looking for!

before I write anything from scratch is there a built in function for this?

Kirill Rakhman
  • 42,195
  • 18
  • 124
  • 148
Mark Gilchrist
  • 1,972
  • 3
  • 24
  • 44

2 Answers2

65

Since Kotlin v1.1 you can use:

"ED05265A".toLong(radix = 16)

Until then use the Java's Long.parseLong.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
voddan
  • 31,956
  • 8
  • 77
  • 87
15

You can simply use

java.lang.Long.parseLong("ED05265A", 16)

Or

import java.lang.Long.parseLong 

[...] 

parseLong("ED05265A", 16)

Kotlin is compatible with Java, and you can, and should, use Java's built-in classes and methods.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • When using Integer.parseInt("ffff0000", 16) , I get exception: NumberFormatException: For input string: "ffff0000" . How come? – android developer Oct 29 '17 at 14:12
  • 1
    It's larger than the max integer value. – JB Nizet Oct 29 '17 at 14:19
  • But on Java it works fine, and is easy to read because in this case it's a representation of a color (red color in this case). Suppose I have an hexa-decimal value that I used fine in Java, what should I set its value in Kotlin? Do I really have to manually convert it myself? – android developer Oct 29 '17 at 14:23
  • 1
    No, it doesn't work in Java. You'd need to use parseUnsignedInt(). – JB Nizet Oct 29 '17 at 14:24
  • Correct. I thought it will also work (never needed to use it, so forgot it has this issue), because my use case is on something else. Please consider checking this question: https://stackoverflow.com/q/47001467/878126 – android developer Oct 29 '17 at 14:41
  • "Kotlin is compatible with Java" is true only on JVM target, but not on Javascript or native targets. There you won't find any java.lang.Long. – Pointer Null Aug 05 '19 at 18:07