darkchampionz
darkchampionz

Reputation: 1234

Lua - Hex to float

The hexadecimal value of 0x40130020 is a float value of 2.296883, using this site http://gregstoll.dyndns.org/~gregstoll/floattohex/. How can this be implemented to Lua? If I use:

x = 0x40130020
print(x)

then the result 1074987040 is printed of course... What should I do? Thanks

Upvotes: 6

Views: 3621

Answers (1)

lhf
lhf

Reputation: 72362

You can do this easily in Lua 5.3:

x=0x40130020
s=string.pack("i4",x)
f=string.unpack("f",s)
print(f)

string.pack and string.unpack are new in Lua 5.3.

In previous versions, you'll need an external library written in C or dive into the innards of the IEEE float representation (which is not too hard). See for instance this question.

Upvotes: 5

Related Questions