[Tcl] How to know decimal representation of binary float

I wrote experimental script to convert binary float to decimal.

References:
http://www.h-schmidt.net/FloatApplet/IEEE754.html

http://sandbox.mc.edu/~bennet/cs110/flt/ftod.html

set exponent 00000001
set mantissa 10001001001101110100110
 
binary scan [binary format B* $exponent] c exponent
set exponent [expr {$exponent - 127}]
 
if {$exponent <= -127} {
	set mantissa "$mantissa"
} else {
	set mantissa "1$mantissa"
}
 
set i 0
set sum 0.0
foreach b [split $mantissa {}] {
	set sum [expr {$sum + pow(2,$exponent-$i)*$b}]
	incr i
}
puts $sum
#=> 1.80555933856e-038

コメントを残す

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください