Reputation: 1919
If I do have an input stream of decimal numbers, e.g.
100 2000 599 232
and I pass them to awk, how do I print them in Hexadecimal notation?.
for example
0x64 0x74D 0x257 0xE8
starting script ...
echo "100 2000 599 232" | awk '{ print $1 }' #here print in hexa instead of decimal
Upvotes: 2
Views: 945
Reputation: 2805
quick caveat - mawk 1.3.4 has severe limitations when it comes to printing octal and hex codes :
$ gawk 'BEGIN{ printf("%\043.16x\n",8^8*-1-2) }'
0xfffffffffefffffe
$ nawk 'BEGIN{ printf("%\043.16x\n",8^8*-1-2) }'
0xfffffffffefffffe
$ mawk 'BEGIN{ printf("%\043.16x\n",8^8*-1-2) }'
0000000000000000
$ mawk2 'BEGIN{ printf("%\043.16x\n",8^8*-1-2) }'
0xfffffffffefffffe
It's not even that large a value (-16777218), and mawk 1.3.4 completely bellyflops. On the flip side, it can directly decipher some hex constants (only gawk not in either posix or traditional mode can directly decipher octal constants :
$ mawk 'BEGIN { OFMT="%.f"; print +"0xDEADBEEF" }'
3735928559
nawk 'BEGIN { OFMT="%.f"; print +"0xDEADBEEF" }'
3735928559
$ mawk2 'BEGIN { OFMT="%.f"; print +"0xDEADBEEF" }'
0
$ gawk --posix 'BEGIN{ OFMT="%.f"; print +"0xDEADBEEF" }'
3735928559 <==== note the difference - posix mode only can decipher strings
the "+" in front is also necessary cuz gawk will just print
it as a string otherwise.
$ gawk -e 'BEGIN { OFMT="%.f"; print 0xDEADBEEF }'
3735928559 <==== standard mode only can decipher clear text ones
- mawk2 is the only one among those above that even prints anything out with %p in printf(), but still erroring out, as such mawk2: line 1: invalid control character 'p' in [s]printf format ("0x10f0099da
- both gawk and nawk properly prints out %a
Upvotes: 0
Reputation: 126203
You can use printf in awk with a format string to convert to hex:
awk '{ printf "%x\n", $1 }'
Upvotes: 4