Posted to tcl by evilotto at Thu Feb 20 18:05:56 GMT 2014view pretty

proc scan_bits {format data} {
    binary scan $data B* bitstring
    set rv {}
    set cursor 0
    foreach field $format {
        set tl [split $field :]
        set fmttype [lindex $tl 0]
        set len [lindex $tl 1]
        set mv [string range $bitstring $cursor $cursor+[expr {$len-1}]]
        set pbs [binary format b* [string reverse $mv]]
        binary scan $pbs\0\0\0 $fmttype ov
        lappend rv $ov
        incr cursor $len
    }
    return $rv
}

# example
scan_bits {i:4 i:4} => {4 1}