DvP
DvP

Reputation: 11

Reversing Endianess C

I'm lost on bit shifting operations, I'm trying to reverse byte order on 32 bit ints, what I've managed to look up online I only got this far but cant seem to find why its not working

int32_t swapped = 0;         //  Assign num to the tmp 


for(int i = 0; i < 32; i++)
{

   swapped |= num & 1; // putting the set bits of num

   swapped >>= 1; //shift the swapped Right side 

   num <<= 1;  //shift the swapped left side 

}

And I'm printing like this

num = swapped;

for (size_t i = 0; i < 32; i++)
{
    printf("%d",(num >> i));
}

Upvotes: 1

Views: 451

Answers (1)

robthebloke
robthebloke

Reputation: 9668

Your code looks likes its attempting to swap bits, and not bytes. If you are wanting to swap bytes, then the 'complete' method would be:

int32_t swapped = ((num >> 24) & 0x000000FF) |
                  ((num >>  8) & 0x0000FF00) |
                  ((num <<  8) & 0x00FF0000) |
                  ((num << 24) & 0xFF000000);

I say 'complete', because the last bitwise-and can be omitted, and the first bitwise-and can be omitted if num is unsigned.

If you want to swap the bits in a 32bit number, your loop should probably max out at 16 (if it's 32, the first 16 steps will swap the bits, the next 16 steps will swap them back again).

int32_t swapped = 0;
for(int i = 0; i < 16; ++i)
{
  // the masks for the two bits (hi and lo) we will be swapping
  // shift a '1' to the correct bit location based on the index 'i'
  uint32_t hi_mask = 1 << (31 - i);
  uint32_t lo_mask = 1 << i;

  // use bitwise and to mask out the original bits in the number
  uint32_t hi_bit = num & hi_mask;
  uint32_t lo_bit = num & lo_mask;

  // shift the bits so they switch places
  uint32_t new_lo_bit = hi_bit >> (31 - i);
  uint32_t new_hi_bit = lo_bit << (31 - i);

  // use bitwise-or to combine back into an int
  swapped |= new_lo_bit;
  swapped |= new_hi_bit;
}

Code written for readability - there are faster ways to reverse the bits in a 32bit number. As for printing:

for (size_t i = 0; i < 32; i++)
{
    bool bit = (num >> (31 - i)) & 0x1;
    printf(bit ? "1" : "0");
}

Upvotes: 2

Related Questions