Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash shell Decimal to Binary base 2 conversion

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 

Is there a simple method to do this without looking at every individual number?

I would prefer not to have to write a lot of code.

like image 371
Daniel Del Core Avatar asked Apr 23 '12 10:04

Daniel Del Core


People also ask

How do you convert binary to decimal to base 2?

To convert a number from binary to decimal using the positional notation method, we multiply each digit of the binary number with its base, (which is 2), raised to the power based on its position in the binary number.

How do I convert to base 2?

Steps To Convert From Base 10 to Base 2-Divide the given number (in base 10) with 2 until the result finally left is less than 2. Traverse the remainders from bottom to top to get the required number in base 2.

How do you convert decimal to binary and binary to decimal?

An easy method of converting decimal to binary number equivalents is to write down the decimal number and to continually divide-by-2 (two) to give a result and a remainder of either a “1” or a “0” until the final result equals zero.


1 Answers

You can use bc as:

echo "obase=2;$ip1" | bc 

See it

like image 84
codaddict Avatar answered Oct 21 '22 02:10

codaddict