My code looks like this:
proc decimalToBin { decNum numBits } {
set one "1"
set zero "0"
set rd ""
for { set jj 0 } { $jj < $numBits } { incr jj } {
if { [expr {$decNum % 2}] > 0 } {
set rd "$one$rd"
} else {
set rd "$zero$rd"
}
set decNum [expr $decNum / 2]
}
return $rd
}
set List_Of_Values_To_Sweep {0 1 63 255}
foreach i {$List_Of_Values_To_Sweep} {
set temp [decimalToBin $i 8]
}
I get an error that looks like this:
ncsim: *E,TCLERR: can't read "List_Of_Values_To_Sweep": no such
variable.
while executing "expr $decNum % 2"
How can I convert a value in the list so that it plays nicely with the %
operand?
Remove the braces around $List_Of_Values_To_Sweep
. They prevent variable substitution, so the string "$List_Of_Values_To_Sweep" (with a literal dollar sign) is assigned to i
and used in the loop, which means that the decnum
argument to decimalToBin
will also be this string instead of the numeric value you intended. Double evaluation inside the condition means that the code tries to perform variable substitution on the string, but as there is no variable named List_Of_Values_To_Sweep
inside decimalToBin
, it fails with the error message you quoted.
Also, the if
condition is evaluated as if passed to expr
, so you don't need to call expr
inside it:
if { $decNum % 2 > 0 } {
Then again, you don't even need it. You can replace the whole if
construct with
set rd [expr {$decNum % 2}]$rd
since that expr
invocation will give you the one or zero that you want.