简体   繁体   中英

Binary Algorithm C Programming

So I have an algorithm designed to take in a 32 bit char array and translate it into its proper decimal equivalent.

double calculateDecimal(char *string){
    char *temp=string;
    double total=0;
    int i;
    int count=31;
    int x=pow(2,count);
    for(i=0;i<32;i++){
        if(!strncmp(temp,"1",1){
            printf("%d + %d\n",x,total);
            total+=x;
        }
        temp++;
        count--;
        x=pow(2,count);
    }
    printf("%d\n",total);
    return total;

}

1) My printf statements have proved that the proper 1's are being read and their proper powers are being calculated. What I have discovered is total and x keep equaling the same power which I'm confused about because I'm on the cusp.

2)My example calculation was 00000000100000010000000000000111 which if i typed in correctly should be the decimal equivalent of 84554151. Thanks for any contributions because I know I am close.

If it's a 32-bit input, why not use a 32-bit integer to contain the result? The pow function is a floating point operation, which makes the task harder. Consider bit operations instead.

int toInt(char *str)
{
  int val = 0;
  while (*str) 
    val = (val << 1) | (*str++ == '1');
  return val;
}

Also note that by shifting the previous result left (multiplying by 2) each time a new character is found, this will work with any string up to 32 bits long.

Well, your code actually has a syntax error here (missing closing bracket):

if(!strncmp(temp,"1",1){

Regarding your problem of binary --> decimal conversion, I would recommend Horner's method of evaluating polynomials: http://en.wikipedia.org/wiki/Horner%27s_method

View the binary expansion as a polynomial where each coefficient is either 0 or 1. Evaluating this polynomial for x = 2 gives you the actual value, which you can print in decimal:

long calculateValue(char * string) {
    long result = 0;
    while(*string){
        result = ((*string) - '0') + result * 2;
        string++;
    }
    return result;
}

(And please don't use pow() and other floating-point functions for integer operations - especially for calculating powers of 2)

BTW, you can use this approach for evaluating numbers written in any base:

long calculateValue(char * string, int base) {
    long result = 0;
    while(*string){
        result = ((*string) - '0') + result * base;
        string++;
    }
    return result;
}

Of course this works for base 1-10, because '9' is followed by ':' in the ASCII table, but you get the idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM