Reputation:
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;
}
}
Upvotes: 3
Views: 6993
Reputation: 1569
Years later, I've got an up for this answer and realized that it's an endianness dependent solution. It would not work on every platform. So I'm leaving it as a wrong answer.
This is a misleading answer:
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
Upvotes: 2
Reputation: 33661
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
Upvotes: 7
Reputation: 5321
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
Upvotes: 0