I am learning bit manipulation using C. I encountered a problem when writing a program that converts a binary to decimal, particularly in the for loop of the program. The following is my code:
unsigned int binary_to_uint(const char *b)
{
unsigned int result = 0;
int i, len;
if (!b)
return (0);
len = strlen(b);
for (i = 0; i < len; i++)
{
if (b[i] == '1')
{
result += 2 << (i-1); /*where my issue is*/
}
else if (b[i] == '0')
continue;
else
return (0);
}
return (9);
}
I tried debugging and I realized my problem was originating from the if statement
I therefore did some experiment with the code in the if* statement:
int main() {
// Write C code here
int i = 0;
printf("result of 2 << (%d - 1): %d\n", i, 2 << (i - 1));
printf("result of 2 << (0 - 1): %d", 2 << (0 - 1));
return 0;
}
In the first printf, displays result of 2 << (0 - 1): 0 in the console, while in the second printf, displays result of 2 << (0 - 1): 1 in the console. My expectation is that both printf should display the exact same thing, that is the value of 2 << -1 is 1, however that is not the case. Can someone please help me understand what is going on. why did the use of the variable i change the outcome of the shift operator to 0?
%din this format string but I only see one argument.printf("result of 2 << (%d - 1): %d\n", 2 << (i - 1));