awkbinarydecimal

AWK Convert Decimal to Binary


I want to use AWK to convert a list of decimal numbers in a file to binary but there seems to be no built-in method. Sample file is as below:

134218506
134218250
134217984
1610612736
16384
33554432

Solution

  • Here is an awk way, functionized for your pleasure:

    awk '
    function d2b(d,  b) {
        while(d) {
            b=d%2b
            d=int(d/2)
        }
        return(b?b:0)
    }
    {
        print d2b($0)
    }' file
    

    Output of the first three records:

    1000000000000000001100001010
    1000000000000000001000001010
    1000000000000000000100000000
    

    Output for 0, -1 and -2:

    0
    -1
    -10