Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make calculations on hexadecimal numbers with awk?

Tags:

hex

awk

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 ;-) )

like image 301
Didier Trosset Avatar asked Sep 10 '10 08:09

Didier Trosset


People also ask

How are hex numbers calculated?

Hex addition involves calculating basic decimal addition while converting between hex and decimal when values larger than 9 (the numerals A through F) are present. In the example above, B + 8 in decimal is 11 + 8 = 19. 19decimal is 13hex, since there is 1 set of 16, with 3 left over.

What is 0x11 in Dec?

0x11. Hexadecimal 11, decimal value 17.

How do you read a hexadecimal table?

The first nine numbers (0 to 9) are the same ones commonly used in the decimal system. The next six two-digit numbers (10 to 15) are represented by the letters A through F. This is how the hex system uses the numbers from 0 to 9 and the capital letters A to F to represent the equivalent decimal number.

How do you read base16?

Base-16 uses 16 values: the numbers 0 to 9 and the letters A to F. Up to the number 9 the decimal and hexadecimal systems are identical: a base-10 number 9 is also a 9 in base-16. We don't have a single number for ten, which is why base-16 uses the letters A to F. The letter A is 10, B is 11 etc.


2 Answers

gawk has the strtonum function:

% echo 0x12345678 | gawk '{ printf "%s: %x - %x\n", $1, $1, strtonum($1) }'
0x12345678: 0 - 12345678
like image 83
glenn jackman Avatar answered Oct 15 '22 19:10

glenn jackman


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
like image 23
schot Avatar answered Oct 15 '22 21:10

schot