Can someone help me understand this code?
int reverse_endianess(int value) {
int resultat = 0;
char *source, *destination;
int i;
source = (char *) &value;
destination = ((char *) &resultat) + sizeof(int);
for (i = 0; i < sizeof(int); i++)
*(--destination) = *(source++);
return resultat;
}
I can't understand this part of code:
destination = ((char *) &resultat) + sizeof(int);
for (i = 0; i < sizeof(int); i++)
*(--destination) = *(source++);
The following causes destination
to point to the byte that follows resultat
(as long as resultat
is an int
):
destination = ((char *) &resultat) + sizeof(int);
It could also have been written as follows:
destination = (char *)(&resultat + 1);
The following is just a simple memory copy loop:
for (i = 0; i < sizeof(int); i++)
*(--destination) = *(source++);
It's equivalent to the following:
for (i = 0; i < sizeof(int); i++) {
--destination; // Point to the one byte earlier.
*destination = *source; // Copy one byte.
source++; // Point to one byte later.
}
Program flow (assuming 32-bit int
and 8-bit char
)
After setup:
source value
+----------+ +---+---+---+---+
| -------+ | a | b | c | d |
+----------+ | +---+---+---+---+
| ^
+------+
destination resultat
+----------+ +---+---+---+---+
| -------+ | 0 | 0 | 0 | 0 |
+----------+ | +---+---+---+---+
| ^
+----------------------+
After one pass of the loop:
source value
+----------+ +---+---+---+---+
| -------+ | a | b | c | d |
+----------+ | +---+---+---+---+
| ^
+----------+
destination resultat
+----------+ +---+---+---+---+
| -------+ | 0 | 0 | 0 | a |
+----------+ | +---+---+---+---+
| ^
+------------------+
When it's done:
source value
+----------+ +---+---+---+---+
| -------+ | a | b | c | d |
+----------+ | +---+---+---+---+
| ^
+----------------------+
destination resultat
+----------+ +---+---+---+---+
| -------+ | d | c | b | a |
+----------+ | +---+---+---+---+
| ^
+------+