Scala十六进制字符串到整数转换

时间:2017-06-14 19:43:58

标签: scala type-conversion

在Scala中,我似乎无法将十六进制字符串转换回整数:

val cols = Array(0x2791C3FF, 0x5DA1CAFF, 0x83B2D1FF, 0xA8C5D8FF,
      0xCCDBE0FF, 0xE9D3C1FF, 0xDCAD92FF, 0xD08B6CFF,
      0xC66E4BFF, 0xBD4E2EFF)

cols.map({ v => Integer.toHexString(v)}).map(v => Integer.parseInt(v, 16))

我收到以下错误消息:

java.lang.NumberFormatException: For input string: "83b2d1ff"
  at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
  at java.lang.Integer.parseInt(Integer.java:583)
  at $anonfun$3.apply(<console>:12)
  at $anonfun$3.apply(<console>:12)
  at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:245)
  at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:245)
  at scala.collection.IndexedSeqOptimized$class.foreach(IndexedSeqOptimized.scala:33)
  at scala.collection.mutable.ArrayOps$ofRef.foreach(ArrayOps.scala:186)
  at scala.collection.TraversableLike$class.map(TraversableLike.scala:245)
  at scala.collection.mutable.ArrayOps$ofRef.map(ArrayOps.scala:186)
  ... 35 elided

2 个答案:

答案 0 :(得分:1)

Int太小了。使用长。

scala> 0x83B2D1FFDL
res3: Long = 35352551421

scala> java.lang.Long.decode("0x83B2D1FFD")
res4: Long = 35352551421

并返回

scala> java.lang.Long.toHexString(res3)
res5: String = 83b2d1ffd

答案 1 :(得分:1)

尝试将其作为无符号值。

cols.map(Integer.toHexString).map(Integer.parseUnsignedInt(_, 16))