Reputation: 19
for(i = 0; bitstr[i] != '\0'; i++){
if(!(bitstr[i]=='0' || bitstr[i]=='1')){
printf("Not a valid bitstring!");
exit(0);
}
else{
sum = sum*2+bitstr[i];
}
}
printf("%d", sum);
When I enter 101 for instance, it prints 339, when it should print 5 as the answer. I am not sure what I am doing wrong. Any help would be much appreciated.
Upvotes: 0
Views: 72
Reputation: 153547
The solution provided by @dasblinkenlight is correct in that one needs to subtract a '0'
within the loop.
Strong suspect another issue.
The "101" entered does not detail which digits are most significant as "101" and its reverse are the same. Nor does it show how bitstr[]
was entered.
The usual assumption is that the left most digit is most significant and that the data was entered with the Most Significant digits first. So a change of indexing is also needed.
char bitstr[100];
int sum = 0;
scanf("%s", bitstr);
size_t i,l;
l = strlen(bitstr); // add
for(i = 0; bitstr[i] != '\0'; i++){
if(!(bitstr[l-1-i]=='0' || bitstr[l-1-i]=='1')){
printf("Not a valid bitstring!");
exit(0);
}
else{
sum = sum*2+ (bitstr[l-1-i] - '0'); // change index and subtract '0'
}
}
printf("%d", sum);
Recommend to re-order the for()
loop from strlen(bitstr) - 1
to 0
and simplify the index calculation. Left "as is" to match OP.
Upvotes: 0
Reputation: 726639
This is because '1'
and '0'
are characters '1'
and '0'
, not integer values. You need to subtract '0'
from them to obtain numeric values:
sum = sum*2+(bitstr[i]-'0');
Upvotes: 5