Version 5 of to.binary

Updated 2007-11-05 16:44:25 by LV

GPS 4 Dec 2003:


 # Purpose: 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}]"} }

See also: Binary representation of numbers