quantum231
quantum231

Reputation: 2593

Converting between hex and float (IEEE 754) in TCL

Does TCL contain built in procedure to convert between a 32-bit or 64-bit hex value and its float or double representation respectively? Here I am from referring to conversion in both directions, into hex and from hex.

Upvotes: 0

Views: 900

Answers (1)

Schelte Bron
Schelte Bron

Reputation: 4813

You can use a combination of binary format and binary scan:

binary scan [binary format f 3.14] H* hex
puts $hex; # c3f54840
binary scan [binary format d 3.14] H* hex
puts $hex; # 1f85eb51b81e0940

And for the reverse, use:

binary scan [binary format H* 1f85eb51b81e0940] d double

The f and d format specifiers will use the machine's native representation. If you need a specific endianness, use r or R for floats and q and Q for doubles. In both cases the lower case versions are for little-endian and the upper case versions are for big-endian.

So for little-endian hex to float:

binary scan [binary format H* c3f54840] r float

Upvotes: 2

Related Questions