问题
I can only use bitwise operations and pointer arithmetic to solve this problem. I am converting from binary to unsigned int.
The function I am writing is:
unsigned int atob(const char* nptr);
atob("101") should return 5, atob("11000") should return 24, atob("11$") should return 3, and atop("") should return 0.
I'm pretty new to bitwise operations, so I really need some help specifically in that area.
edit:
nptr can only be incremented, not other inc/dec's are allowed.
回答1:
unsigned bits2val(char *bits)
{
unsigned val;
for (val = 0; *bits; bits++) {
if (*bits == '1')
val = (val << 1) | 1;
else if (*bits == '0' )
val <<= 1;
else
break;
}
return val;
}
回答2:
Here's my example implementation, using just shifts and ors (assuming you can use ++ for string-manipulation):
unsigned atob(const char *input)
{
unsigned result = 0;
unsigned currentBit = 0;
// we need to go right to left;
const char *end = input;
// make sure we only read '0's and '1's
while ((*end == '0') || (*end == '1'))
{
end++;
}
while (--end >= input) {
// check for overflow
if ((currentBit >> 3) > sizeof(result))
break;
char isCurrentBitSet = *end == '1';
unsigned setValue = (isCurrentBitSet << currentBit);
result |= setValue;
currentBit++;
}
return result;
}
回答3:
Start with the basics http://www.wikihow.com/Convert-from-Decimal-to-Binary
来源:https://stackoverflow.com/questions/11310796/binary-to-unsigned-int-using-bitwise-operations-and-pointer-arithmetic-in-c