MikeA
MikeA

Reputation: 33

is there a way to convert an integer to be always a 4 digit hex number using Lua

I'm creating a Lua script which will calculate a temperature value then format this value as a 4 digit hex number which must always be 4 digits. Having the answer as a string is fine.

Previously in C I have been able to use

data_hex=string.format('%h04x', -21)

which would return ffeb

however the 'h' string formatter is not available to me in Lua dropping the 'h' doesn't cater for negative answers i.e

data_hex=string.format('%04x', -21)

print(data_hex)

which returns ffffffeb

data_hex=string.format('%04x', 21)

print(data_hex)

which returns 0015

Is there a convenient and portable equivalent to the 'h' string formatter?

Upvotes: 3

Views: 2526

Answers (1)

Richard Chambers
Richard Chambers

Reputation: 17593

I suggest you try using a bitwise AND to truncate any leading hex digits for the value being printed.

If you have a variable temp that you are going to print then you would use something like data_hex=string.format("%04x",temp & 0xffff) which would remove the leading hex digits leaving only the least significant 4 hex digits.

I like this approach as there is less string manipulation and it is congruent with the actual data type of a signed 16 bit number. Whether reducing string manipulation is a concern would depend on the rate at which the temperature is polled.

For further information on the format function see The String Library article.

Upvotes: 3

Related Questions