问题
I want to set first three bytes of an integer to 0 in C++. I tried this code, but my integer variable a
is not changing, output is always -63. What am I doing wrong?
#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;
}
}
回答1:
Just use bitwise and (&
) with a mask, there is no reason for loop:
a &= 0xFF000000; // Drops all but the third lowest byte
a &= 0x000000FF; // Drops all but the lowest byte
(Thanks to @JSF for the corrections)
As noted by @black, you may use Digit separators since C++14 in order to make your code more readable:
a &= 0xFF'00'00'00; // Drops all but the third lowest byte
a &= 0x00'00'00'FF; // Drops all but the lowest byte
回答2:
You need &=
instead of |=
.
回答3:
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
回答4:
If you really mean "first" not lowest, then take advantage of the fact that alias rules let char alias anything:
int a = 4294967233;
char* p=&a;
...
p[0] = whatever you wanted there
p[1] = whatever you wanted there
p[2] = whatever you wanted there
来源:https://stackoverflow.com/questions/34357968/how-to-set-first-three-bytes-of-integer-in-c