首页 > 解决方案 > Scala:如何正确解析 0~FFFF 范围内的十六进制值,确保我总是以 16 位结束,因为每个位都有自己的价值?

问题描述

我需要解码包含十六进制值的字符串。

十六进制值需要解码为 16 位,每个位都有自己的含义。

我尝试使用以下代码,但它是错误的,而且似乎并不总是 16 位,一旦十六进制值被解码。

我花了很多时间试图解决这个问题,但不能,所以如果有人能帮助我,我将不胜感激。

谢谢!

Here are some Hex examples:
A42
800   
242
0
2
4000

> val stat = BigInt(hexVal, 16).toString(2)
> for (s <- stat.indices) {
>      s match {
>        case 0 => bit1 = stat.substring(s, s+1) 
>        case 1 => bit2 = stat.substring(s, s+1)
>        case 2 => bit3 = stat.substring(s, s+1)
>        case 3 => bit4 = stat.substring(s, s+1)
>        case 4 => bit5 = stat.substring(s, s+1)
>        case 5 => bit6 = stat.substring(s, s+1)
>        case 6 => bit7  = stat.substring(s, s+1) 
>        case 7 => bit8 = stat.substring(s, s+1)
>        case 8 => bit9 = stat.substring(s, s+1) 
>        case 9 => bit10 = stat.substring(s, s+1) 
>        case 10 => bit11  = stat.substring(s, s+1) 
>        case 11 => bit12 = stat.substring(s, s+1) 
>        case 12 => bit13 = stat.substring(s, s+1)
>        case 13 => bit14  = stat.substring(s, s+1)
>        case 14 => bit15 = stat.substring(s, s+1)
>        case 15 => bit16 = stat.substring(s, s+1)
>      }

标签: scalahexbit

解决方案


一种选择是使用具有以下f格式的字符串插值:

val v = BigInt(BigInt(hexVal, 16).toString(2), 10)

val stat = f"$v%016d"

推荐阅读