0
votes

I am trying to save a list of numbers in binary format (floating point single) but Tcl cant save it correctly and I could not gain to correct number when i read the file from vb.net

set outfile6 [open "btest2.txt" w+]
fconfigure stdout  -translation binary -encoding binary
set aa {}
set p 0
for {set i 1} {$i <= 1000 } {incr i} {
  lappend aa [expr (1000.0/$i )]
  puts -nonewline $outfile6 [binary format "f" [lindex $aa $p]]
  incr p
}
close $outfile6
1
Welcome. You seem to miss the brackets around lindex, like so: [lindex $aa $p]. - mrcalvin
Yes it is corrected. - Amirhossein Najafi

1 Answers

0
votes

Tcl cant save it correctly

There are two glitches in your snippet:

  • the missing brackets for nested command evaluation around lindex (see my comment): [lindex $aa $p]
  • you fconfigured the stdout, rather than your file channel: fconfigure $outfile6 -translation binary

With this fixed, the following works for me:

set outfile6 [open "btest2.txt" w+]
fconfigure $outfile6 -translation binary
set aa {}
set p 0
for {set i 1} {$i <= 1000 } {incr i} {
  lappend aa [expr (1000.0/$i )]
  puts -nonewline $outfile6 [binary format "f" [lindex $aa $p]]
  incr p
}

close $outfile6

Suggestions for improvement

Your snippet seems overly complicated to me, esp. the loop construct. Simplify to:

  • Better use [scan %f $value] to explicitly turn a value into the floating point representation, rather than [expr]?
  • [binary format] takes a counter or wildcard, like f*, to process multiple values: [binary format "f*" $aa]
  • You don't need the loop variables p, use [lindex $aa end]; or better a loop variable to hold the single added element (rather than to collect it from the list again).
  • -translation binary implies -encoding binary