Let me start with the code:
#include <iostream> unsigned reverse0(unsigned); union FourBytes { unsigned value; unsigned b1 : 8; unsigned b2 : 8; unsigned b3 : 8; unsigned b4 : 8; }; unsigned reverse1(unsigned); int main(void) { std::cout << reverse0(2) << std::endl << reverse1(2) << std::endl; return 0; } unsigned reverse0(unsigned p) { unsigned res(0); for (int i(0); i < sizeof(p)*8; ++i) { unsigned ithBit( (p & (1<<i)) >> i); //get ith bit int byteNumber(sizeof(p) - (i / 8) - 1); // get the current byte we are working with res |= ithBit << byteNumber*8+i; // set corresponding bit in res } return res; } unsigned reverse1(unsigned p) { FourBytes fb; fb.value = p; FourBytes res; res.b4 = fb.b1; res.b3 = fb.b2; res.b2 = fb.b3; res.b1 = fb.b4; return res.value; }
My intention is to figure out how bit manipulations in C++ work. I am trying to implement two methods of reversing the machine word (as far as I get it – the machine word is the same as any data type which consists of 4 bytes). But so far it seems like no one of my methods work. I am very confused. Help me, please.
First and foremost I would like to get comments which would explain what I am doing wrong and how I can fix it. And then I would like to get comments on how I can utilize the best coding practices here and how I can improve performance (if possible). Will be grateful for any other kinds of useful comments.