O'Reilly logo

Learning AWK Programming by Shiwang Kalkhanda

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Converting decimal to binary

In the following example, we give a list of decimal numbers as input to the AWK program, which returns the binary equivalent output on screen. This program reads the decimal number then finds the remainder of that number on division by 2, using the modulus operator. The remainder is stored in a string until the division of the number by 2, returns the 0 as follows:

$ vi list.txt10201540
$ vi dec2bin.awkBEGIN    {    Print "\tDisplay Binary equivalent of Decimal number "    }func getnumber(decimal,temp, binary){    binary = "";    temp=decimal;    while( temp )        {        if ( temp%2==0 )        {            binary = "0" binary;                }        else        {            binary = "1" binary;                }        temp = int(temp/2);     }        return binary;}{    binval=getnumber( $1 );    print $1, " --> ", binval}$ awk -f ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required