Version 4 of to.binary

Updated 2003-12-05 19:08:44

GPS 4 Dec 2003:


 # Purpose: ???

 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


Category Algorithm