shell 使用Tcl将二进制比特流拆分为N个相等大小

mxg2im7a  于 2023-02-16  发布在  Shell
关注(0)|答案(1)|浏览(116)

我有一个数字,比如10101100100011101010111010。我想把它分成N个大小相等的块,假设我想要一个输出:1010 1100 1000 1110 1010 1110 10我想用Tcl来做,有什么想法吗?
我使用了for循环,我能够分割输出中的第一个块,我能够得到1010,但不能分割其余的块。

33qvvth1

33qvvth11#

我不会说tcl,但是一些manpage查找给了我:

#!/usr/bin/tclsh

proc str2chunksize { s cs } {
    set len [ string length $s ]

    for {set i 0; set j -1} {$i < $len} {incr i $cs} {
        incr j $cs
        lappend resultList [ string range $s $i $j ]
    }
    return $resultList
}

proc str2numchunks { s nc } {
    set len [ string length $s ]
    set cs0 [ expr int(floor(double($len)/$nc)) ]
    set excess [ expr $len % $nc ]

    for {set n 0; set i 0; set j -1} {$n < $nc} {incr n} {
        set cs [ expr $n < $excess ? $cs0 +1 : $cs0 ]
        incr j $cs
        lappend resultList [ string range $s $i $j ]
        incr i $cs
    }
    return $resultList
}

set chunks [ str2chunksize "10101100100011101010111010" 4 ]
puts [ join $chunks " " ]

set chunks [ str2chunksize "10101100100011101010111010" 7 ]
puts [ join $chunks " " ]


set chunks [ str2numchunks "10101100100011101010111010" 4 ]
puts [ join $chunks " " ]

set chunks [ str2numchunks "10101100100011101010111010" 7 ]
puts [ join $chunks " " ]

set chunks [ str2numchunks "10101100100011101010111010" 17 ]
puts [ join $chunks " " ]

set chunks [ str2numchunks "10101100100011101010111010" 30 ]
puts [ join $chunks ":" ]

输出:

1010 1100 1000 1110 1010 1110 10
1010110 0100011 1010101 11010
1010110 0100011 101010 111010
1010 1100 1000 1110 1010 111 010
10 10 11 00 10 00 11 10 10 1 0 1 1 1 0 1 0
1:0:1:0:1:1:0:0:1:0:0:0:1:1:1:0:1:0:1:0:1:1:1:0:1:0::::

相关问题