
Following the
recent post about my issues with byte swapping on amd64, I have received several answers.. Since comments were broken, Rupert sent me a good explanation of the cryptic code from OSS4. Let me remember you what it was doing:
static inline short
bswap_16 (short x)
short y = 0;
unsigned char *a = ((unsigned char *) &x) + 1;
unsigned char *b = (unsigned char *) &y
*b++ = *a--;
*b++ = *a--;
return y;
The code is indeed very simple, but it has to be decomposed carefully.. First, the author assumes that
unsigned char = one byte, which seems reasonable. Then,
a is initialised at the second character of the two-characters value
x, and
b on the first of the returned (swapped) value
y. Now, the two cryptic lines can be decomposed as follows:
*(b++) = *(a--), which literally means "put in
b the value from
a, and then increase
b and decrease
a. When executing the second line,
a points to the first character from
x, and
b to the second from
y. As Rupert noticed, the second call could simply have been
*b = *a, but this wouldn't have been l33t enough :) Now, about the original code, namely
(x 8) (x >> 8), MadCoder (salut !), as well as another anonymous comment both suggested that this would be a type error. Indeed, I had noticed the wrong right shift, but no matter how I tried, with or without mask, with
unsigned short,
short, or
uint16_t, as suggested by MadCoder, I always get the same corrupted sound.. So, thanks for your comments, I'm now trying to dig the issue down in the code that makes use of this function. Most likely the issue comes from a wrong transtyping there.. I am also wondering what's the efficiency of the above OSS4's code with regard to
(x 8) (x >> 8). Any idea ? PS: Yes, text on comments are mangled a lot. This is a basic safehtml protection, and I don't have the control over it, sorry..