# Bit shift (swap bytes) as this really works?

Hello.

As I swam with shifts of bits. Task - to change the order of the bytes in an int

``````unsigned int econv(unsigned int from) {
unsigned int value = from;
std::cout << std::hex << "original:" << from << " : "<< sizeof(value) << std::endl;

value |= (from & 0xFF000000) >> 24;
// allocate from the original first byte, move it to the end and through "OR" apply changes
std::cout << from << ">> 24 " << value << std::endl;
value |= (from & 0x00FF0000) >> 8;
// allocate the second byte and shift it to 3rd place
std::cout << from << ">> 8 " << value << std::endl;
value |= (from & 0x0000FF00) << 8;
// if the shift to the right all okay, then shifted to the left of the problem - value is not changed here at all, am I doing it wrong?
std::cout << from << "<< 8 " << value << std::endl;
value |= (from & 0x000000FF) << 24;
// right shift the last byte in the 1st position is also not reflected in the result
std::cout << from << "<< 24 " << value << std::endl;

return value;
}``````

Everything shifts to the right do not affect the result and I in an emphasis I can not understand where exactly I "floated"? I can not properly understand the essence of the changes?

Like using "bitwise And" properly allocate bytes, and then shift to the desired position and is applied to the result via the "bitwise OR"...
June 10th 19 at 16:06
1 answer
June 10th 19 at 16:08
Solution
Corny first need `unsigned value = 0`;
You kind of make a full order, but the initial assignment is incorrect.

UPD. Checked in — so.
E-my nadozh was so lohanutsya )) Thank you.

"It is necessary to draw on a blank canvas"
"It is necessary to draw on a blank canvas"
"It is necessary to draw on a blank canvas" - gino.Stark23 commented on June 10th 19 at 16:11

Find more questions by tags C++