Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion between binary and decimal

Tags:

unix

How do I convert between decimal and binary? I'm working on a Solaris 10 platform

Decimal to Binary
4000000002 -> 100000000000000000000000000010

Binary to Decimal
100000000000000000000000000010 -> 4000000002

I used the following command in unix but it takes lot of time. I have 20 million records like this

For decimal to binary, set obase to 2:

echo 'obase=2;4000000002' | bc 

For binary to decimal, set ibase to 2:

echo 'ibase=2;100000000000000000000000000010' | bc 
like image 260
user446069 Avatar asked Jun 12 '26 18:06

user446069


1 Answers

If you are running bc once for each number that will be slow. Can you not arrange for the data to be delivered to a file and input in one go?

Here's a simple illustration, starting with your numbers in the file called input.txt:

# To binary
$ ( echo 'obase=2;ibase=16;'; cat input.txt ) | bc | paste input.txt - > output.txt

# To hex
$ ( echo 'obase=16;ibase=2;'; cat input.txt ) | bc | paste input.txt - > output.txt

The results are written to the file output.txt.

The paste is included to produce a tab-spearated output result like

07      111
1A      11010
20      100000
2B      101011
35      110101
80      10000000
FF      11111111

showing input value versus output value. If you just want the results you can omit the paste, e.g.:

$ ( echo 'obase=2;ibase=16;'; cat input.txt ) | bc > output.txt

Note that you probably have to set ibase as well as obase for the conversion to be correct. gclswceap1d-mc48191-CRENG_DEV [/home/mc48191/scratch]

like image 71
martin clayton Avatar answered Jun 14 '26 17:06

martin clayton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!