hexadecimal arithmetic in awk

hexadecimal arithmetic in awk

Post by Russell A. Be » Thu, 25 Apr 1996 04:00:00



        I want to do hex arithmetic using awk.  awk seems to presume that
all numbers are decimal, that any string containing characters other than
0-9 must not be a number.
thanks, russell bell
 
 
 

hexadecimal arithmetic in awk

Post by susan cassi » Tue, 30 Apr 1996 04:00:00




Quote:>    I want to do hex arithmetic using awk.  awk seems to presume that
>all numbers are decimal, that any string containing characters other than
>0-9 must not be a number.
>thanks, russell bell

When I needed to do this type of thing, I could not get nawk/awk to
accept a multi-command pipeline as input to getline, so I had to call
a little bc script to do the actual math.  Here is a sample script:

#create a script that will be used later to do hex arithmetic
#this example adds 4 to a hex value
#if you are going to use this all the time, keep the script we are
#  creating, and delete this part of this script
echo 'val=`echo $1|tr "[a-z]" "[A-Z]"`' > /tmp/bcincrementscr
echo '(echo "obase=16;ibase=16;$val + 4;quit")|bc|tr "[A-F]" "[a-f]" ' \
  >> /tmp/bcincrementscr
    chmod ugo+x /tmp/bcincrementscr

nawk '
     function increment_hex (inputval)  {
     commandtxt=sprintf("/tmp/bcincrementscr %s \> /tmp/nawktmp",inputval)
     system (commandtxt)
     getline tempval <"/tmp/nawktmp"
     close ("/tmp/nawktmp")
     return tempval
   }

   {
   #take the first field in the file, and using it as a hex value, add 4
    newval=increment_hex($1)
    printf("%s %s\n",$1,newval) }' <testin
rm /tmp/bcincrementscr /tmp/nawktmp

If file testin looks like this:
0f
1a
ff

Your output looks like this:
0f 13
1a 1e
ff 103

I hope this helps.
--
Susan Cassidy


 
 
 

1. AWK hexadecimal to decimal

In an awk script I want to translate a hexadecimal number to a decimal number.
Does someone know how this can be done ?
--
 _________________________________________________
/                                                 \

|  Lindelaan 3, B-2288 Grobbendonk, Belgium       |
|   ______                                        |
|   \    /   A desk is a dangerous place          |
|    \  /    from which to view the world.        |
|     \/                   - John le Carre        |
\_________________________________________________/

2. YACC/LEX parsing help needed ../

3. Converting hexadecimal to decimal in (awk) script

4. TRS-80-Model100 termcap entry

5. awk and floating point arithmetic

6. DNS w/ Intra & Internet

7. Hex arithmetic in AWK

8. FIN_WAIT_2

9. force awk to do an arithmetic comparison for shell variables

10. How to add characters to a file in hexadecimal mode?

11. awk: best way to handle multiple files with awk ?

12. How to make gcc -S generate hexadecimal values, not decimal

13. Sorting hexadecimal values