Updated 2015-11-07 16:57:46 by pooryorick

Note: In Tcl 8.6, format %b was introduced to perform this operation.

GPS 2003-12-04:

See Also  edit

Binary representation of numbers

Description  edit

To convert a decimal number to a binary representation:
proc to.binary n { 
    incr n 0
    set r {} 
    while {$n > 0} { 
        set r [expr {$n & 1}]$r
        set n [expr {$n >> 1}]
    } 
    return $r
}

Example:
% to.binary 3
11
% to.binary 4
100
% to.binary 200
11001000

JPT:

Here's a recursive one-liner that could certainly be optimized:
proc to.binary n {expr {!$n ? 0 : [to.binary [expr {$n>>1}]][expr {$n&1}]}}

AMG Here's another method:
proc to.binary {n} {
    binary scan [binary format I $n] B* out
    return [string trimleft [string range $out 0 end-1] 0][string index $out end]
}