我想在C++中将整数的前三个字节设置为0.我尝试了这段代码,但我的整数变量a没有改变,输出总是-63.我究竟做错了什么?
#include <iostream>
#include <string>
int main()
{
int a = 4294967233;
std::cout << a << std::endl;
for(int i = 0; i< 24; i++)
{
a |= (0 << (i+8));
std::cout << a << std::endl;
}
}
Run Code Online (Sandbox Code Playgroud)
只需使用bitwise和(&)与掩码,没有理由循环:
a &= 0xFF000000; // Drops all but the third lowest byte
a &= 0x000000FF; // Drops all but the lowest byte
Run Code Online (Sandbox Code Playgroud)
(感谢@JSF的更正)
如@black所述,您可以使用C++ 14以来的数字分隔符,以使您的代码更具可读性:
a &= 0xFF'00'00'00; // Drops all but the third lowest byte
a &= 0x00'00'00'FF; // Drops all but the lowest byte
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3049 次 |
| 最近记录: |