Binary to Decimal

448 Views Asked by At

Is it possible to convert a binary pattern to decimal pattern consists of 0's and 1's without loop (iterations).

Suppose if I have.

Binary Pattern          I need in Decimal
1                           1
10                          10
100                         100

I need it in c-programming, So binary pattern I have in integer (int).

Binary Pattern    number             I need in Decimal
1                  1       * 1                 1
10                 2       * 5                 10
100                4       * 25                100
1000               8       *                   1000

* means multiply 

So what I need a mathematical equation that gives me 10(number-1), without loop. This is power function actually but we don't have power operator in C language.

First, I don't know whether I am asking for impossible thing?

2

There are 2 best solutions below

1
On BEST ANSWER

Given $m=2^n$, you are needing to compute $n$. You need to compute binary logarithm. I don't think you can compute it without a loop, unless your hardware has a function that essentially computes it. See here examples of functions that are equivalent and hardware supporting their computation.

The answer may also depend on how you actually store the input $m$. If it is written in memory in binary, you just need to print it. Whether this requires a loop or not depends on the language.

0
On

Given a non-zero integer number a which is assumed to be a power of 2, $a = 2^n$ (you can check this with a & (a-1) == 0), you can get the corressponding power of 10 with pow(10,floor(log(a)/log(2)+0.5)).