二进制无符号整数当使用C位运算和指针运算 [英] Binary to unsigned int using bitwise operations and pointer arithmetic in C
本文介绍了二进制无符号整数当使用C位运算和指针运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只能用位运算和指针算法来解决这个问题。我从二进制转换为unsigned int类型。
我写的功能是:
unsigned int类型ATOB(为const char * NPTR);
ATOB(101)应返回5,ATOB(11000)应返回24,ATOB(11 $)应返回3和顶部()应返回0
我是pretty新位运算,所以我真的需要一些帮助,特别是在该区域。
编辑:
NPTR只能递增,而不是其他增/减的都是允许的。
解决方案
无符号bits2val(字符*位)
{
无符号VAL; 为(VAL = 0; *比特;比特++){
如果(*位=='1')
VAL =(VAL&所述;&所述; 1)| 1;
否则,如果(*位=='0')
VAL&所述;&下; = 1;
其他
打破;
} 返回VAL;
}
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.
解决方案
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;
}
这篇关于二进制无符号整数当使用C位运算和指针运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文