二进制到无符号int,使用C中的按位运算和指针运算

我只能使用按位运算和指针运算来解决这个问题。 我正在从二进制转换为unsigned int。

我写的function是:

unsigned int atob(const char* nptr); 

atob(“101”)应返回5,atob(“11000”)应返回24,atob(“11 $”)应返回3,atop(“”)应返回0。

我对按位操作很新,所以我真的需要一些专门的帮助。

编辑:

nptr只能递增,而不允许其他inc / dec。

 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; } 

这是我的示例实现,只使用shift和ors(假设您可以使用++进行字符串操作):

 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; } 

从基础知识开始http://www.wikihow.com/Convert-from-Decimal-to-Binary