I'm having trouble figuring out what exactly I'm missing in this Byte reversal method. For example is should take 0x01020304 and flip the bits to 0x04030201.
I've attached my output giving the errors and here is my code:

/* 
 * reverseBytes - reverse the bytes of x
 *   Example: reverseBytes(0x01020304) = 0x04030201
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 25
 *   Rating: 3
 */
int reverseBytes(int x) {
    printf("x is %d\n", x);
    x = (x & 0x7FFFFFFF );
    printf("x is %d\n", x);
    x = ((x&0xF0) >>4) | ((x&0x0F) << 4);
    x = ((x&0xCC) >>2) | ((x&0x33) << 2);
    return  ((x&0xAA) >>1) | ((x&0x55) << 1);

  return x;
}

I can't figure out what I'm missing/what needs fixing this is as far as I can get. I can't modify the method name or parameter types and can't use loops/conditionals. Any input/help would be appreciated!

Recommended Answers

All 4 Replies

If your doing a straight rev of bytes why are you stripping the first bit x = (x & 0x7FFFFFFF );

Also, you might get more info from your print statements if you use the hex format character %x - like printf("x is %x\n", x);

I'm having trouble figuring out what exactly I'm missing in this Byte reversal method. For example is should take 0x01020304 and flip the bits to 0x04030201.

So the 01 of 0x01020304 needs to move 24 bits to the right.
And the 02 of 0x01020304 needs to move 8 bits to the right.
And the 03 of 0x01020304 needs to move 8 bits to the left.
And the 04 of 0x01020304 needs to move 24 bits to the left.

I don't think you're shifting things far enough.

At line 12 you are working on one byte, means interchanging last 2 nibbles.
so after line 12 executes x becomes 0x00000040.
X has lost its original value. You cannot operate on x in two statements.
This can be done if you take other variable.
But for x you need something like this

x = x << 24 | (x & 0xff00) << 8 | (x & 0xff0000) >> 8 | x >> 24
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.