printf Hexadecimal output

printf "%X\n" "A"
41

printf "%X\n" "2"
2
Expected 32 (not 2).

Is there a "printf" which will output the hexadecimal value of a numeric character?

$ printf "%d\n" 0xA
10
$ printf "%d\n" 0x20
32
$ printf "%X\n" 10
A
$ printf "%X\n" 32
20

@Scrutinizer,

Methyl means the ascii code of the character "2" in hexadecimal, which should be 32.

I think the question you meant to ask is

If this is the correct question, then the answer is no.

@Franklin: Oops...

$ printf "%X\n" \'A
41
$ printf "%X\n" \'2
32
2 Likes

Thanks Scrutinizer. It's just unbroken my script!

Just for interest I had been having a go at this post but expanding the problem to any character.

http://www.unix.com/aix/150117-convert-clear-text-into-binary.html

@Scrutinizer

Where is the \'[value] syntax documented for POSIX shells? I do not think I've seen it. Or more likely I ignored it....

For example:

echo $(( \'A  + 1 ))

fails in ksh88 on Solaris 10.

This does not:

> printf "%d\n" \'A
65

All it does is make a literal quote char followed by A. The behavior must be a printf thing, telling it to interpret the following char as an integer... It seems to work on OSX as well as linux, so it might cover BSD and its descendants too.

Here: printf
The second bullit point after point 11:

2 Likes

The quote tip is really good. It also works for octal as well as hexadecimal.
I'm still refining an answer to:
http://www.unix.com/aix/150117-convert-clear-text-into-binary.html
Currently I'm converting each character to octal using "printf" then converting the octal character to binary using "bc". It is chronically inefficient ... but it works.
The only reason to go via octal rather than hexadecimal is to create a symmetrical reverse translation path back to the original characters to prove the conversion.