Manawyrm
Manawyrm

Reputation: 241

Hex to int32-Value

I'm currently trying to convert a hex string into its value as a signed int.

Example:

0000000E - 14
FFFFFFF2 - -14

So: converting the value for unsigned values is easy:

print(tonumber("0000000E", 16)) // outputs 14

negative values can be parsed like this:

num = tonumber("FFFFFFF2", 16)
print(4294967296 - num - num)

but unfortunatly, I need to detect, whether the MSB is set for this to work. This would be easy, if my lua implementation would support the Bit-Library, but unfortunatly that isn't the case.

So: How can I convert signed hex-integers into a LUA number?

Upvotes: 3

Views: 2440

Answers (1)

Jakuje
Jakuje

Reputation: 25966

The best answer is probably by Egor from comments:

num = (tonumber("FFFFFFF2", 16) + 2^31) % 2^32 - 2^31

Upvotes: 2

Related Questions