我有表示十六进制值的字符串,这些值包含多个不同位长的字段。我必须把它们提取出来并打印在屏幕上。例如,0x17AF018D1是一个33位十六进制值,其中位索引为0到32;我需要超出包含在位0-5、6-7、8-21、22-30、31-32中的数字。
我敢肯定,做这件事有多种方法。实现这一目标的最佳方法是什么?
发布于 2020-08-05 08:00:51
十六进制值可以直接视为整数。Tcl的整数实际上是任意的精确值,但经过优化可以有效地处理主机系统的机器字大小。(Tcl透明地为您处理细节。)
这意味着位字段提取器可以是这样的(假设是小endian):
proc BitField {value from to} {
if {$from > $to} {
error "reversed bit field description"
}
# How many bits wide is the field?
set width [expr {$to - $from + 1}]
# Convert the width into a bit mask in the lowest bits
set mask [expr {(1 << $width) - 1}]
# Shift and mask the value to get the field
expr {($value >> $from) & $mask}
}
set abc 0x17AF018D1
puts [BitField $abc 0 5]
puts [BitField $abc 6 7]
puts [BitField $abc 8 21]
puts [BitField $abc 22 30]
# You are aware this overlaps?
puts [BitField $abc 30 32]对于不重叠的连续字段,可以这样做:
# Note that this is big endian as it is working with the string representation
scan [format "%033lb" $abc] "%3b%8b%14b%2b%6b" e d c b a
puts $a
puts $b
puts $c
puts $d
puts $e字符串中的值是整体值/字段宽度:%033lb表示格式为33位二进制值(在您的示例中为101111010111100000001100011010001),而%3b则在此时解析一个3位二进制值。(不幸的是,由于我们刚刚生成的输入数据中没有空格,所以scan说明符之间不能有空格,所以我们不能让它更容易读懂。)
https://stackoverflow.com/questions/63257191
复制相似问题