2

I have been reading THIS PAGE (among others) but still can't find my answer.

I'm trying to get Lua to convert an 8 bit value (i.e., an integer from 0 to 255) into a 2 Byte Ascii representation of the corresponding Hex chars

The only Lua syntax that I know how to use for this purpose is this one...

 MyString =  string.format("%1x", That_Number  )  

... but, when the number is 0 to 15, that syntax gives me: 1 2 3 4 5 6 7 8 9 a b c d e f

... while this is what I really want: 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F

My Question: Is there a simple syntax to guarantee me a "two digit" Ascii representation ?

("simple" means that it's already built into the syntax; not a function that I have to write)

p.s., it would be nice if I could get the A, B, C, D, E, F characters as upper case.

1 Answer 1

6

string.format("%02X", 14))

0 for padding zeros instead of spaces. 2 for a forced width of two characters (not 1 as in your example). X for upper case letter output instead of lower case.

It should be pointed out that essentially none of this answer is Lua specific as those are printf standard sequences and format options.

The Lua reference manual says:

The format string follows the same rules as the printf family of standard C functions. The only differences are that the options/modifiers *, l, L, n, p, and h are not supported and that there is an extra option, q.

so we can infer that the x and X format specifiers are available with the usual width and leading zero modifiers intact.

The same principle applies to a number of Lua library functions. You will often need to refer to the related standard C runtime library function mentioned in the Lua reference to get a complete understanding.

Sign up to request clarification or add additional context in comments.

3 Comments

Ta-Da, thank you Etan. I tried the "02X" as you suggested (with upper case "X" instead of lower, and the leading "0") and all is fixed. Smart guy. Thanks
I boldly extended your very fine answer with links to printf and string.format documentation in hopes that this sort of thing will help future folks finding this question. Extending yours seemed fairer than adding a redundant answer of my own...
@RBerteig Good additions. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.