tags:

views:

41

answers:

1

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 2 crore 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 
+1  A: 

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]

martin clayton
Hi can u explain me what is FOO represents
@user446069 - I've updated the answer. For background on FOO in the original posting see http://en.wikipedia.org/wiki/Here_document - it was just a here document terminator.
martin clayton