Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How do I convert an ASCII char to ASCII HEX in a AWK script?

I want loop by a range of letter

example

for(i="a"; i<"g"; i++)
 print i;

NOTE: I want loop by a range from hex representation and print the character.

share|improve this question

Sounds to me like you don't really need all the characters...

$ awk 'BEGIN { chartable="abcdefghij" ; for (i=index(chartable, "a"); i<index(chartable, "g"); i++) { print substr(chartable, i, 1) } }'
a
b
c
d
e
f
share|improve this answer

Build a table containing all the ASCII characters and use the awk builtin index() to lookup characters in the table. Then use sprintf() to convert the decimal value returned by index() to hex.

BEGIN {
    for (i = 0; i < 128; i++) {
       table = sprintf("%s%c", table, i);
    }
}

function chartohex (char) {
    return sprintf("0x%x", index(table, char));
}

END { # examples
   print chartohex("a");
   print chartohex("A");
   print chartohex("!");
}

Put this code in the file "foo" and run awk -f foo < /dev/null and you'll see the ASCII values for "a", "A" and "!" printed in hexadecimal.

share|improve this answer

You must log in to answer this question.

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