views:

98

answers:

2

All,

I have been practicing coding problems online. Currently I am working on a problem statement Problems where we need to convert Big Endian <-> little endian. But I am not able to jot down the steps considering the example given as:

123456789 converts to 365779719

The logic I am considering is :
1 > Get the integer value (Since I am on Windows x86, the input is Little endian)
2 > Generate the hex representation of the same.
3 > Reverse the representation and generate the big endian integer value

But I am obviously missing something here.

Can anyone please guide me. I am coding in Java 1.5

+5  A: 

Check this out

int little2big(int i) {
    return((i&0xff)<<24)+((i&0xff00)<<8)+((i&0xff0000)>>8)+((i>>24)&0xff);
}
stacker
Software Monkey
Also, this will switch little to big *and* big to little, so the method name is not broad enough. Perhaps swapEndian?
Software Monkey
Also, I would use | instead of +, on the assumption that the use of bitwise or's is likely to be faster, and easier for the compiler/runtime to optimize.
Software Monkey
+3  A: 

The thing you need to realize is that endian swaps deal with the bytes that represent the integer. So the 8 byte number 27 looks like 0x0000001B. To convert that number, it needs to go to 0x1B000000... With your example, the hex representation of 123456789 is 0x075BCD15 which needs to go to 0x15CD5B07 or in decimal form 365779719.

The function Stacker posted is moving those bytes around by bit shifting them; more specifically, the statement i&0xff takes the lowest byte from i, the << 24 then moves it up 24 bits, so from positions 1-8 to 25-32. So on through each part of the expression.

For example code, take a look at this utility.

Bryan
+1: Valuable additional details.
Software Monkey