1

I am trying to convert hex to decimal to ascii and store it in a variable. I am using the following code.

HEX=30
DEC=`printf "%d\n" 0x${HEX}`
echo "$DEC"
ASC=`printf \\$(printf '%03o' $DEC)`
echo "$ASC"

I am getting the following error syntax error :

`(' unexpected

I am using Solaris 10, and ksh. I do not want to use a function for ascii and call it to store the value. I want to be able to do it without using a function.

0

2 Answers 2

2

You're mistakenly escaping the $ twice, leading printf to see printf \$( ... instead of (what I assume you want) of substituting the inside printf results. To that end, you could simplify that whole statement to: ASC=$(printf '%03o' $DEC)

6
  • its not giving the right value. For a Hex number of 34, The ASCII value must be 0. Intead its giving out 060. Something's not correct. Commented Jun 24, 2015 at 4:21
  • Your script is taking a hex value, converting it to decimal (%d), then converting it again to octal (%o).
    – Jeff Schaller
    Commented Jun 24, 2015 at 4:25
  • Yeah. i was told that we have to convert to octal to get ascii value in shell script. Do you know any other way of getting ascii value of hexa? Commented Jun 24, 2015 at 4:39
  • @ayrton_senna what do you mean by "ascii value"? A character? Commented Jun 24, 2015 at 22:50
  • I am confused. ASCII is a character encoding. Hex and octal are different bases for numbers. The only common ground here is (possibly) an alternate base representation of an ASCII character.
    – Jeff Schaller
    Commented Jun 24, 2015 at 22:51
2

Thanks Jeff Schaller for correcting my syntax error. I found a solution to my problem, this is working in Solaris 10.

script:

#!/bin/ksh
HEX=30
DEC=`printf "%d\n" 0x${HEX}`  ##Converted Hex to decimal
echo "$DEC"
OCT=$(printf '%o' $DEC)   ##Converted decimal to octal
echo "$OCT"
ASCI=$(printf \\$OCT)  ##Finally converted OCTAL to ASCII.
echo "$ASCI"

output:

48
60
0

Apparently, we have to convert decimal to octal before printing out to ASCII.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .