如何设置整数的前三个字节?在 C++ 中
How to set first three bytes of integer? in C++
我想在 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;
}
}
您需要 &=
而不是 |=
。
只用带掩码的按位与(&
),没有循环的原因:
a &= 0xFF000000; // Drops all but the third lowest byte
a &= 0x000000FF; // Drops all but the lowest byte
(感谢@JSF 的更正)
正如@black 所指出的,您可以使用 Digit separators 自 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
如果你的意思是 "first" 不是最低的,那么利用别名规则让 char 别名任何东西的事实:
int a = 4294967233;
char* p=&a;
...
p[0] = whatever you wanted there
p[1] = whatever you wanted there
p[2] = whatever you wanted there
多年后,我得到了这个答案,并意识到这是一个依赖字节顺序的解决方案。它不适用于每个平台。所以我将其作为错误答案。
这是一个误导性的回答:
union also could be a choice
union my_type{
int i;
unsigned int u;
...
unsigned char bytes[4];
};
...
my_type t;
t.u = 0xabcdefab;
t.bytes[0] = 5; // t.u = 0x05cdefab
我想在 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;
}
}
您需要 &=
而不是 |=
。
只用带掩码的按位与(&
),没有循环的原因:
a &= 0xFF000000; // Drops all but the third lowest byte
a &= 0x000000FF; // Drops all but the lowest byte
(感谢@JSF 的更正)
正如@black 所指出的,您可以使用 Digit separators 自 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
如果你的意思是 "first" 不是最低的,那么利用别名规则让 char 别名任何东西的事实:
int a = 4294967233;
char* p=&a;
...
p[0] = whatever you wanted there
p[1] = whatever you wanted there
p[2] = whatever you wanted there
多年后,我得到了这个答案,并意识到这是一个依赖字节顺序的解决方案。它不适用于每个平台。所以我将其作为错误答案。
这是一个误导性的回答:
union also could be a choice
union my_type{ int i; unsigned int u; ... unsigned char bytes[4]; }; ... my_type t; t.u = 0xabcdefab; t.bytes[0] = 5; // t.u = 0x05cdefab