Warm tip: This article is reproduced from stackoverflow.com, please click
formatting padding tcl zero

zero padding in TCL

发布于 2020-05-01 18:09:46

My tcl code looks like this:

set writes 1a8000028020900

binary scan [binary format H* $writes] B* bits
puts "$bits"

Output:

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

If input hex value is of even length there would be no padding. If it is odd, like in the example above, zeros are getting padded.

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?

Questioner
Manoj Kumar
Viewed
37
mrcalvin 2020-02-13 07:28

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