swap bytes in a ushort/ulong
-
What is the fasted way to swap bytes in a ushort/ulong? For example: 0x1234 -> 0x3412 0x12345678 -> 0x78563412
unsigned short short_exch(const unsigned short a) { // 0x1234 -> 0x3412 return (a << 8) + (a >> 8); }; unsigned long long_exch(unsigned long a) { // 0x12345678 -> 0x78563412 unsigned long t = a&0xff; a >>= 8; t <<= 8; t += a&0xff; a >>= 8; t <<= 8; t += a&0xff; a >>= 8; t <<= 8; return t + a; };
Jürgen Eidt http://cpicture.de/en
-
What is the fasted way to swap bytes in a ushort/ulong? For example: 0x1234 -> 0x3412 0x12345678 -> 0x78563412
unsigned short short_exch(const unsigned short a) { // 0x1234 -> 0x3412 return (a << 8) + (a >> 8); }; unsigned long long_exch(unsigned long a) { // 0x12345678 -> 0x78563412 unsigned long t = a&0xff; a >>= 8; t <<= 8; t += a&0xff; a >>= 8; t <<= 8; t += a&0xff; a >>= 8; t <<= 8; return t + a; };
Jürgen Eidt http://cpicture.de/en
-
Try a union :
typedef union { ULONG itemlong; UCHAR itemchar[4]; } UnionLong;
then you can swap the bytes through a temporary variable. a two cent stamp short of going postal.Didn't thought of a union :) But even swapping with the xor trick I'm not sure how the compiler optimization would be. I guess looking at the asm code would make the final judgement. Thanks. Jürgen Eidt http://cpicture.de/en
-
What is the fasted way to swap bytes in a ushort/ulong? For example: 0x1234 -> 0x3412 0x12345678 -> 0x78563412
unsigned short short_exch(const unsigned short a) { // 0x1234 -> 0x3412 return (a << 8) + (a >> 8); }; unsigned long long_exch(unsigned long a) { // 0x12345678 -> 0x78563412 unsigned long t = a&0xff; a >>= 8; t <<= 8; t += a&0xff; a >>= 8; t <<= 8; t += a&0xff; a >>= 8; t <<= 8; return t + a; };
Jürgen Eidt http://cpicture.de/en
unsigned long Swap(unsigned long value)
{
return ((value & 0xFF000000) >> 24) |
(value & 0x00FF0000) >> 8) |
(value & 0x0000FF00) << 8) |
(value & 0x000000FF) << 24);
}
Software Zen:
delete this;
-
unsigned long Swap(unsigned long value)
{
return ((value & 0xFF000000) >> 24) |
(value & 0x00FF0000) >> 8) |
(value & 0x0000FF00) << 8) |
(value & 0x000000FF) << 24);
}
Software Zen:
delete this;
Thanks Gary, that a good way to do it! Jürgen Eidt http://cpicture.de/en
-
Thanks Gary, that a good way to do it! Jürgen Eidt http://cpicture.de/en
You're welcome. If you make the function
inline
, the compiler will compile it in place without the function call overhead (I forgot to do that).
Software Zen:
delete this;
-
You're welcome. If you make the function
inline
, the compiler will compile it in place without the function call overhead (I forgot to do that).
Software Zen:
delete this;
Of course inline! Actually you can remove the masking for the 24 bit shifts. For the inner two bytes I don't see an improvement. Thanks Gary for the follow up :) Jürgen Eidt http://cpicture.de/en