AWK Help

HI All,

Need a help

Suppose I have a file having the data

1,FF,233

where the second field is Hex
now I want to convert this hex in dec and see the output as

1,255,233

Request you all to help

Regards,
Gaurav Goel

If you have Python, here's an alternative

for line in open("file"):
    line = line.strip().split(",")
    print "%s,%s,%s" % (line[0],str(int(line[1],16)), line[2])

otherwise, people have rolled out these functions in awk (i have not used them). you can have a try

function hex2dec(x,    h, i, n, l) {
    h = "0123456789ABCDEF..........abcdef"
    for (i = l = length(x); i > 0; i--)
        n += (index(h, substr(x, i, 1)) - 1) % 16 * 16 ^ (l - i)
    return n

}

function dec2hex(d) {
    return sprintf("%lx", d)

} 

Using printf

#/bin/ksh
for v in $(cut -d, -f2 /tmp/hex) ; do
   printf '%d\n' "0x$v"
done

Using bc

#/bin/ksh
 for v in $(cut -d, -f2 /tmp/hex) ; do
   print "ibase=16;$v" |bc
 done

cat /tmp/hex
1,FF,233
1,EF,233

Output:
255
239

Hi Gurus,
Please let us know if the following awk can be used for the above conversion,

 awk -F, ' { printf("The Decimal value of %s is [%x]\n", $2,$2) }'  /tmp/hex

I tried it but always gives me 0 for hexadecimal value.

Thanks
Nagarajan Ganesan

In ksh...

#! /usr/bin/ksh
typeset -i16 xf2
typeset -i10 df2
typeset -l f2
while IFS=, read f1 f2 f3 ; do
        xf2=16#$f2
        ((df2=xf2))
        echo  $f1,$df2,$f3
done
exit 0

You can convert decimal to hexa and not the reverse using printf.

awk -v VAR=A 'END{ printf"%s %s\"%s\n", "echo \"ibase=16;", VAR, " | bc" }' /dev/null | sh

Well, thats kind of possible! :slight_smile:

What i meant was, its not possible using format specifiers provided in printf.