如何在scala中将十六进制长字符串转换为BigInt

时间:2019-06-18 07:14:35

标签: string scala hex bigint

我有一个很长的十六进制字符串。     VAL hexStr = “6579ba5175087ae94f289dc46b4aab805217d7c0372f68631442e0950b535a3a2c566cacd4c8f367e68d39fd07e88adcc3e6497dc793c2dcad994dd3b5c4b74a20e816695d82856b0d8c2853141bb9bb2236c6ddc07b60075fe37d5f60287e0b542c6c47ec172883e79adf83d19163d698c50ab8e70d862ae4ea38964031c97d”

val hexMap = ('A' to 'F').zipWithIndex.map{case  (c,i) => (c, i+10) }.toMap
def toHex(str: String) = {
      def toDec:PartialFunction[Char, Int] = {
        case c if hexMap.isDefinedAt(c)=>
          hexMap(c)
        case c  => c.asDigit
      }
      val h = str.reverse.zipWithIndex
      h.foldLeft(BigInt(0)){ case (x,(c,i)) =>  x + (BigInt(toDec(c)) * (BigInt(16) pow i))
      }
    }

呼叫toHex(hexStr) 将产生

-108510794603240369573054864637132287318772867810563957913302194314864518557374668031774623887439510929033883541346004435263772843343293163699936959100821415781894682693381965433598320482583614884522426697017992684587643668557555164019950155571119830400184127425065856214285578629986381577449968065171417872003

编辑: 字符串似乎有错误,无论如何,建议的解决方案要好得多

1 个答案:

答案 0 :(得分:5)

BigInt(hexStr, 16)
//res0: scala.math.BigInt = 71258518882991221199875654441770186043024830083666699360127886842868157248126295100933853434968025092086230338525388922395016925471123458792910471538652708595873210731483519842703899118662479234930656255067013084250507013784907717453962954969707406763166383259520442025661667308493334727385388264452806265213