gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 11:49:02 57 4
gpt4 key购买 nike

我有一个很长的十六进制字符串。 val hexStr = "6579ba5175087ae94f289dc46b4aab805217d7c0372f68631442e0950b535a3a2c566cacd4c8f367e68d39fd07e88adcc3e6497dc793c2dcad994dd3b5c4b74 a20e816695d82856b0d8c2853141bb9bb2236c6ddc07b60075fe37d5f60287e0b542c6c47ec172883e79adf83d19163d698c50ab8e70d862ae4ea38964031c97d"

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

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

最佳答案

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

关于string - 如何在scala中将长十六进制字符串转换为BigInt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56643624/

57 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com