Search code examples
linuxunixawknawk

UNIX:How to convert ip address to binary code


Is there is any Command to convert ip address in to binary form?

Eg: 10.110.11.116

output: 00001010.01101110.00001011.01110100


Solution

  • Well, here's one (very convoluted) way to do it:

    pax> export ip=10.110.11.116
    
    pax> for i in $(echo ${ip} | tr '.' ' '); do echo "obase=2 ; $i" | bc; done
         | awk '{printf ".%08d", $1}' | cut -c2-
    00001010.01101110.00001011.01110100
    

    The echo/tr statement gives you a space-separated list of the octets and the for processes these one at a time.

    For each one, you pass it through bc with the output base set to 2 (binary). Those four lines of variable length binary numbers then go through awk to force them to a size of 8, put them back on a single line, and precede each with a . and the final cut just removes the first ..

    I'm almost certain there are better ways to do this of course but this shows what you can do with a bit of ingenuity and too many decades spent playing with UNIX :-)