scala - 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)
> }
解决方案
一种选择是使用具有以下f
格式的字符串插值:
val v = BigInt(BigInt(hexVal, 16).toString(2), 10)
val stat = f"$v%016d"
推荐阅读
- javascript - 如何用一些动态值替换跨度内容
- angular - Angular 6如何管道http调用
- python - 执行此操作时如何构建 Python 应用程序可以在 Raspberry Pi 上启动 Web 服务器和 Python 程序?
- java - spring boot:如何从应用程序属性配置数据源
- google-apps-script - 根据多个答案转到下一页 - 谷歌表格
- ruby-on-rails - 如何为具有基本身份验证的 Rails 应用程序编写集成 minitest 代码?
- mysql - Mysql根据特定列删除相似的行,除了id最高的行
- macos - Swift - 从另一个类调用 reloadData() 失败(找到 nil),但从 self 类调用成功
- socket.io - 无法在 socket.on 之外获取数据
- javascript - 如何使用键盘在 svg 路径中移动对象