Friday, June 15, 2012

How to make calculations on hexadecimal numbers with awk? - Stack Overflow

hex - How to make calculations on hexadecimal numbers with awk? - Stack Overflow


I have a file containing a list of hexadecimal numbers, as 0x12345678 one per line.
I want to make a calculation on them. For this, I thought of using awk. But if printing an hexadecimal number with awk is easy with the printf function, I haven't find a way to interpret the hexadecimal input other than as text (or 0, conversion to integer stops on the x).
awk '{ print $1; }'                     // 0x12345678
awk '{ printf("%x\n", $1)}'             // 0
awk '{ printf("%x\n", $1+1)}'           // 1                 // DarkDust answer
awk '{ printf("%s: %x\n", $1, $1)}'     // 0x12345678: 0
Is it possible to print, e.g. the value +1?
awk '{ printf(%x\n", ??????)}'          // 0x12345679
Edit: One liners on other languages welcomed! (if reasonable length ;-) )
link|edit

feedback

3 Answers


In the original nawk and mawk implementations the hexadecimal (and octal) numbers are recognised.gawk (which I guess you are using) has the feature/bug of not doing this. It has a command line switch to get the behaviour you want: --non-decimal-data.
echo 0x12345678 | mawk '{ printf "%s: %x\n", $1, $1 }'
0x12345678: 12345678

echo 0x12345678 | gawk '{ printf "%s: %x\n", $1, $1 }'
0x12345678: 0

echo 0x12345678 | gawk --non-decimal-data '{ printf "%s: %x\n", $1, $1 }'
0x12345678: 12345678
link|edit
feedback

gawk has the strtonum function:
% echo 0x12345678 | gawk '{ printf "%s: %x - %x\n", $1, $1, strtonum($1) }'
0x12345678: 0 - 12345678
link|edit
feedback

You can convert the string into a number, simply by doing $1 + 0. AWK automagically converts a string to a number as needed. So you can do:
awk '{ printf "%X\n", $1+1; }'
or if you want 0x1234 notation:
awk '{ printf "0x%X\n", $1+1; }'
link|edit
This does not work on my Linux system (debian): It prints 1. My guess is that awk tries to interpret the value as decimal and stops right after the 0, on the x, ignoring that 0x is an hexadecimal notation prefix. – Didier Trosset Sep 10 '10 at 8:27
Was this post useful to you?     


'via Blog this'

No comments:

Post a Comment