tags:

views:

67

answers:

2

i have following problem To decode the Biquinary code use the number 5043210. At each digit multiply the biquinary number by the number 5043210. This will give you one decimal digit. For example take the number 0110000. To change this into decimal: (5 × 0) + (0 × 1) + (4 × 1) + (3 × 0) + (2 × 0) + (1 × 0) + (0 × 0) = 4 i have tried this one

#include <iostream>
using namespace std;
int main(){

    char a[]="5043210";
    int sum=0;
    int b=48;
    int n=sizeof(a)/sizeof(char);
     for (int i=0;i<n;i++){

         sum+=(a[i]-'0')*(b>>(1<<(n-1-i)));

     }

     cout<<sum<<endl;


     return 0;
}

but unfortunately it gives me wrong answer please help

+2  A: 

I was able to produce the answer 4 by simplifying the code a bit. I reversed the order of a[] and used std::bitset to make the code easier and clearer.

#include <bitset>
#include <iostream>

int main()
{
    char a[] = "0123405";
    std::bitset<7> bits(48);
    int sum = 0;
    for (int i = 0; i < 7; ++i)
        sum += (a[i]-'0')*bits[i];

    std::cout << sum << std::endl;
    return 0;
}
Kristo
yes but do you think that it will be correct for any case? i mean in case of other variable?
@user457463, the `7` is a magic number that's tied to the length of the 5043210 code value. As long as the value you're decoding will fit in a number of bits less than or equal to that length, you should be fine.
Kristo
+1  A: 

Try changing (b>>(1<<(n-1-i))) to just (b>>(n-1-i)&1).

Edit: Forgot to mention that the given program also counts the null terminator on the string. The computation of n should subtract one to correct for it: int n=sizeof(a)/sizeof(char)-1;.

Boojum
i have got 7 why?