I have some C code that I’d like to port to java. I haven’t done much C coding, but I was able to follow along up until this one function. If anyone could help me understand what is going on, it would be greatly appreciated.
int reverse_integer(int input) {
int output = 0, i;
for ( i=0, i<sizeof(int); i++ ) {
output = ( input & 0x000000FF ) | output;
input >>= 8;
if ( i < 3 ) {
output <<= 8;
}
}
return output;
}
The function is used as such:
char * position = //some data
/*the included comment on this next line states its the size of a string*/
int i = reverse_integer( *(int*)position )
I’ll be happy to post Java code that does the same as the C code, but only if you promise not to use it.
/** Reverses the bytes in an integer. */ public static int reverseInteger(int input) { return (input >>> 24) | (input >> 8) & 0x0000ff00 | (input << 8) & 0x00ff0000 | (input << 24); }Note that there’s no point in looping – an
intin Java is always 4 bytes. Also note the triple-right angle bracket at the beginning the expression to perform an unsigned right-shift.Now for the reasons not to use it:
1 – The function already exists – see
Integer.reverseBytes(int)2 – You’re going to have a hard time using that example code, since Java doesn’t let you cast an array of bytes as anything else. Java is officially big-endian (most significant byte first), so if you’re reading bytes from a file then you can use
java.io.DataInputStreamto extract ints, longs, etc.