想要连接两个二进制值以获得 16 位值并保存到文件中。
第一个二进制是 6 位常数000111
,第二个二进制从 0 开始,每次循环递增 1。
#!/usr/bin/tclsh
set output_file "output.dat"
set data_number "10"
set output_fpt [open ./${output_file} w]
for {set x 0} {$x < $data_number} {incr x} {
set y [expr $x * (2 ** 22)]
binary scan [binary format I $y] B32 var
set data [binary format B6B12 000111 $var]
fconfigure $output_fpt -translation binary
puts -nonewline $output_fpt $data
}
close $output_fpt
预期输出:1C00 1C01 1C02...
答案1
对于二进制数据,您可能需要使用按位算术运算符:
$ tclsh
% set fixed 0b000111
0b000111
% for {set i 0} {$i < 4} {incr i} {
set n [expr {($fixed << 2 | $i) << 8}]
puts [format {%d => %d = %b = %x} $i $n $n $n]
}
0 => 7168 = 1110000000000 = 1c00
1 => 7424 = 1110100000000 = 1d00
2 => 7680 = 1111000000000 = 1e00
3 => 7936 = 1111100000000 = 1f00
答案2
#!/usr/bin/tclsh
set output_file "output.txt"
set data_number "10"
set output_fpt [open ./${output_file} w]
for {set x 0} {$x < $data_number} {incr x} {
set q [expr ($x + (7 * (2 ** 10))) * (2 ** 16)]
binary scan [binary format I $q] B16 var_q
set data_q [binary format B16 $var_q]
fconfigure $output_fpt -translation binary
puts -nonewline $output_fpt $data_q
}
close $output_fpt