Bash shell Decimal to Binary base 2 conversion

前端 未结 5 1467
情书的邮戳
情书的邮戳 2020-12-01 06:24

I\'m looking for an easy way in Bash to convert a decimal number into a binary number. I have variables that need to be converted:

$ip1 $ip2 $ip3 $ip4
         


        
5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-01 06:44

    Convert decimal to binary with bash builtin commands (range 0 to 255):

    D2B=({0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1})
    
    echo ${D2B[7]}
    

    00000111

    echo ${D2B[85]}
    

    01010101

    echo ${D2B[127]}
    

    01111111


    To remove leading zeros, e.g. from ${D2B[7]}:

    echo $((10#${D2B[7]}))
    

    111


    This creates an array with 00000000 00000001 00000010 ... 11111101 11111110 11111111 with bash‘s brace expansion. The position in array D2B represents its decimal value.

    See also: Understanding code ({0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1})

提交回复
热议问题