Search code examples
cbinaryieee-75416-bit

Converting from Binary to Decimal without using arithmetic operations


I had this written until i realized * is an arithmetic operation.

I want to return a nonnegative integer representation of the binary sequence input. IE. 0x4a returns 74 in decimal

typedef unsigned bit16;

unsigned int bin_to_dec(bit16 x)
{
int dec=0;
int k=0;
int remainder;

while (x!= 0){
    remainder = x%10;
    dec+=remainder*k;
    k=k+2;
    x=x/10;
}

:(

How would I go about this conversion if I can't use arithmetic operations other than +/-?


Solution

  • As + and - are allowed...Instead of multiplying into k*reamainder try looping this way

    int n;//consider new int
    

    In the while loop write first line as

    n=remainder;
    

    Instead of *

    for(i=0;i<k;i++)
        remainder+=n;
    

    This would do the multiplication :).

    And for x%10, construct a function

    int mod(int n)
    {
       int m;
       while(n>0)
       {
          n=n-10;
          m=n;
        }
       return m;
    }
    

    And for x/10 it'd be the same but you must return number of times you subtracted like this :

    int mod(int n)
    {
       int count=0;
       while(n>0)
       {
          count=count+1;
          n=n-10;
       }
       return count;
    }
    

    edit : If + and - are also not allowed try making functions for them using binary operators and use them instead of + and - in the above answer!