在 Scala 中将十六进制字符串转换为 Int、Short 和 Long

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10763730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 04:10:56  来源:igfitidea点击:

Hex String to Int,Short and Long in Scala

scala

提问by rsan

Just can't find a way to transform an Hex String to a number (Int, Long, Short) in Scala.

只是找不到在 Scala 中将十六进制字符串转换为数字(Int、Long、Short)的方法。

Is there something like "A".toInt(base)?

有类似的东西"A".toInt(base)吗?

回答by 7zark7

You can use the Java libs:

您可以使用 Java 库:

val number = Integer.parseInt("FFFF", 16)
> number: Int = 65535

Or if you are feeling sparky :-):

或者,如果你感觉闪闪发光:-):

implicit def hex2int (hex: String): Int = Integer.parseInt(hex, 16)

val number: Int = "CAFE" // <- behold the magic
number: Int = 51966


Also, if you aren't specifically trying to parse a String parameter into hex, note that Scala directly supports hexadecimal Integer literals. In this case:

此外,如果您不是专门尝试将 String 参数解析为十六进制,请注意 Scala 直接支持十六进制整数文字。在这种情况下:

val x = 0xCAFE
> x: Int = 51966

Isn't Scala wonderful? :-)

Scala 是不是很棒?:-)

回答by Sergey Passichenko

7zark7 answer is correct, but I want to make some additions. Implicit from Stringto Intcan be dangerous. Instead you can use implicit conversion to wrapper and call parsing explicitly:

7zark7 答案是正确的,但我想补充一些。从隐StringInt可能是危险的。相反,您可以使用隐式转换来包装并显式调用解析:

class HexString(val s: String) {
    def hex = Integer.parseInt(s, 16)
}
implicit def str2hex(str: String): HexString = new HexString(str)

val num: Int = "CAFE".hex

回答by Benoit

What about a one-liner?

单线呢?

def hexToInt(s: String): Int = {
    s.toList.map("0123456789abcdef".indexOf(_)).reduceLeft(_ * 16 + _)
}

scala> hexToInt("cafe")
res0: Int = 51966

And to answer your second item:

并回答你的第二个项目:

Is there something like "A".toInt(base)?

有没有像 "A".toInt(base) 这样的东西?

Yes, still as a one-liner:

是的,仍然作为单线:

def baseToInt(s: String, base: String): Int = {
    s.toList.map(base.indexOf(_)).reduceLeft(_ * base.length + _)
}

scala> baseToInt("1100", "01")
res1: Int = 12

回答by Andrew E

Anyone wanting to convert a UUID from hex to a decimal number can borrow from Benoit's answer and use BigDecimal for the job:

任何想要将 UUID 从十六进制转换为十进制数的人都可以借鉴 Benoit 的答案并使用 BigDecimal 来完成这项工作:

scala> "03cedf84011dd11e38ff0800200c9a66".toList.map(
 |   "0123456789abcdef".indexOf(_)).map(
 |     BigInt(_)).reduceLeft( _ * 16 + _)
res0: scala.math.BigInt = 5061830576017519706280227473241971302

Or more generally:

或更一般地:

def hex2dec(hex: String): BigInt = {
  hex.toLowerCase().toList.map(
    "0123456789abcdef".indexOf(_)).map(
    BigInt(_)).reduceLeft( _ * 16 + _)
}

def uuid2dec(uuid: UUID): BigInt = {
  hex2dec(uuid.toString.replace("-",""))
}

Then:

然后:

scala> import java.util.UUID

scala> val id = UUID.fromString("3CEDF84-011D-D11E-38FF-D0800200C9A66")
id: java.util.UUID = 03cedf84-011d-d11e-38ff-0800200c9a66

scala> uuid2dec(id)
res2: BigInt = 5061830576017519706280227473241971302

One practical application for this is encoding the UUID in a barcode, where Code128 produces a shorter barcode for all digits than it does with alphanumeric strings. See notes about subtype "128A" on http://en.wikipedia.org/wiki/Code128#Subtypes.

对此的一个实际应用是在条形码中编码 UUID,其中 Code128 为所有数字生成一个比使用字母数字字符串更短的条形码。请参阅http://en.wikipedia.org/wiki/Code128#Subtypes上有关子类型“128A”的注释。

回答by oseiskar

For Long and Short, it is also possible to use the Java methods directly like

对于 Long 和 Short,也可以直接使用 Java 方法,如

Long2long(java.lang.Long.valueOf(hexString, 16))

where Long2longcan be even be omitted in some cases.

Long2long在某些情况下甚至可以省略where 。