简体   繁体   English

如何使用按位运算符将位与C中的无符号整数隔离?

[英]How to use bitwise operators to isolate bits from unsigned ints in C?

this seems to be working well for me except this one time. 除了这一次外,这似乎对我来说运作良好。 I'm trying to get the first 10 bits of this number 我正在尝试获取此数字的前10位

unsigned char c= 17512807u<<22>>22;

I expect this to be 359 or 0101100111 but I'm getting 103 or 0001100111. Is there a reason that this is happening? 我期望这是359或0101100111,但我得到的是103或0001100111。是否有发生这种情况的原因?

The result you are getting is correct due to the truncation to 8-bit unsigned char value (when assigning to c ). 由于截断为8位unsigned char值(分配给c ),因此您得到的结果是正确的。

If you need a value that is 10-bits wide you should use a different datatype, like uint16_t or an unsigned int . 如果您需要一个10位宽的值,则应使用其他数据类型,例如uint16_tunsigned int

Reference to C++ integer datatypes 引用C ++整数数据类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM