Convert an ascii character to ascii hexadecimal representation

0

2

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.

user751132

Posted 2012-05-02T00:25:17.107

Reputation: 141

Answers

1

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

Ignacio Vazquez-Abrams

Posted 2012-05-02T00:25:17.107

Reputation: 100 516

0

awk does not have ord(), chr() functions like python. you have to first make array in BEGIN block which index is ascii character and value is decimal number.

awk 'BEGIN {
 for (i = 0; i <= 255; i++) {
    t = sprintf("%c", i)
    a[t] = i
}

for( i=a["a"]; i < a["g"]; i++)
    print sprintf("%c",i)
}'
a
b
c
d
e
f

mug896

Posted 2012-05-02T00:25:17.107

Reputation: 101

0

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.

Kyle Jones

Posted 2012-05-02T00:25:17.107

Reputation: 5 706