問題描述
TCL 中的零填充 (zero padding in TCL)
我的 tcl 代碼如下所示:
set writes 1a8000028020900
binary scan [binary format H* $writes] B* bits
puts "$bits"
輸出:
0 0 0 1 1 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0
如果輸入的十六進制值是偶數長度,則沒有填充。如果它是奇數,就像上面的例子一樣,零被填充。
如果格式化的位數沒有在字節邊界處結束,最後一個字節的剩餘位將為零。如何避免這種填充?
參考解法
方法 1:
If the number of digits formatted does not end at a byte boundary, the remaining bits of the last byte will be zeros. How to avoid this padding?
Well, you will have to compute and tell binary scan
the targeted number of bits. Maybe there is a more elegant way than this, but why not simply DIY?
% set writes 1a8000028020900
1a8000028020900
% set hexLength [string length $writes]
15
% binary scan [binary format H* $writes] B[expr {$hexLength * 4}] bits
1
% puts $bits
000110101000000000000000000000101000000000100000100100000000
方法 2:
The manual page says:
If arg has fewer than count digits, then zeros will be used for the remaining digits.
The value you are supplying does not specify all 64 bits. The binary
command cannot guess what you want, and pads zeros on to the end of the supplied string.
Edit:
To avoid this, simply define all bits in the value to be converted:
set writes 01a8000028020900
方法 3:
Here's a thought about padding the source string:
binary scan [binary format H* $writes] B* bits
puts "$bits"
binary scan [binary format H* [format "%016s" $writes]] B* bits
puts "$bits"
outputs
0001101010000000000000000000001010000000001000001001000000000000
0000000110101000000000000000000000101000000000100000100100000000
(by Manoj Kumar、mrcalvin、Brad Lanam、glenn jackman)