tags:

views:

27

answers:

1

So dc is a great tool for converting between bases - handy for those bit twiddling coding jobs. e.g to convert 1078 into binary I can do this:

bash> echo "2o1078p" | dc
10000110110

However I can't get it to print fractions between 0 and 1 correctly. Trying to convert 0.3 into binary:

bash> echo "2o10k 0.3p" | dc
.0100

But 0.0100(bin) = 0.25 not 0.3.

However if I construct the value manually I get the right answer

bash> echo "2o10k 3 10 / p" | dc
.0100110011001100110011001100110011

Well it looks like its giving me more than the 10 significant figures I ask for but thats OK

Am I doing something wrong? Or am I trying to make dc do something that its not able to do?

bash> dc --version
dc (GNU bc 1.06) 1.3
...
+1  A: 

Strange. My first thought was that maybe precision only applies to calculations, not conversions. But then it only works for division, not addition, subtraction, or multiplication:

echo "2o10k 0.3 1 / p" | dc

.0100110011001100110011001100110011

echo "2o10k 0.3 0 + p" | dc

.0100

echo "2o10k 0.3 0 - p" | dc

.0100

echo "2o10k 0.3 1 * p" | dc

.0100

As for precision, the man page says "The precision is always measured in decimal digits, regardless of the current input or output radix." That explains why the output (when you get it) is 33 significant bits.

Rick Regan
Interestingly "2o10k 0.3000 p" works OK too .. so something funny is going on with number of s.f. when in a base other than 10.
Michael Anderson