Bash shell Decimal to Binary base 2 conversion

前端 未结 5 1458
情书的邮戳
情书的邮戳 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条回答
  •  Happy的楠姐
    2020-12-01 06:54

    Decimal to Binary using only Bash

    Any integer number can be converted ti binary using it::

    touch dec2bin.bash && chmod +x "$_" && vim "$_"
    

    And, then copy paste the following:

    #!/bin/bash
    num=$1;
    dec2bin()
    {
        op=2; ## Since we're converting to binary
        quo=$(( $num/ $op)); ## quotient
        rem=$(( $num% $op)); ## remainder
        array=(); ## array for putting remainder inside array
        array+=("$rem"); ## array expansion
            until [[ $quo -eq 0 ]]; do
                num=$quo; ## looping to get all remainder, untill the remainder is 0
                quo=$(( $num / $op));
                rem=$(( $num % $op));
                array+="$rem"; ## array expansion
            done
        binary=$(echo "${array[@]}" | rev); ## reversing array
        printf "$binary\n"; ## print array
    }
    main()
    {
    [[ -n ${num//[0-9]/} ]] &&
        { printf "$num is not an integer bruv!\n"; return 1;
        } || { dec2bin $num; }
    }
    main;
    

    For example:

    ./dec2bin.bash $var
    110100100
    

    Integer must be added!!

    ./dec2bin.bash 420.py
    420.py is not an integer bruv!
    

    Also, another way using python: Much slower

    python -c "print(bin(420))"
    0b110100100
    

    Hexadecimal to Binary using only Bash

    Similarly, hexadecimal to binary, as follows using only bash:

    #!/usr/local/bin/bash ## For Darwin :( higher bash :)
    #!/bin/bash ## Linux :)
    hex=$1;
    hex2bin()
    {
        op=2; num=$((16#$hex));
        quo=$(( $num/ $op));
        rem=$(( $num% $op));
        array=();
        array+=("$rem");
            until [[ $quo -eq 0 ]]; do
                num=$quo;
                quo=$(( $num / $op));
                rem=$(( $num % $op));
                array+="$rem";
            done
        binary=$(echo "${array[@]}" | rev);
        printf "Binary of $1 is: $binary\n";
    }
    main()
    {
    [[ -n ${hex//[0-9,A-F,a-f]/} ]] &&
        { printf "$hex is not a hexa decimal number bruv!\n"; return 1;
        } || { hex2bin $hex; }
    }
    main;
    

    For example:

    ./hex2bin.bash 1aF
    Binary of 1aF is: 110101111
    

    Hex must be passed:

    ./hex2bin.bash XyZ
    XyZ is not a hexa decimal number bruv!
    

提交回复
热议问题