Supermodel/Src/Util/ByteSwap.cpp

51 lines
1.3 KiB
C++
Raw Normal View History

2016-08-10 03:27:59 +00:00
#include "Util/ByteSwap.h"
2022-07-11 16:42:15 +00:00
#ifdef _MSC_VER
#include <intrin.h>
#endif
2016-08-10 03:27:59 +00:00
namespace Util
{
2022-07-11 16:42:15 +00:00
void FlipEndian16(uint8_t * const buffer, const size_t size)
2016-08-10 03:27:59 +00:00
{
2022-07-11 16:42:15 +00:00
#ifdef _MSC_VER
uint16_t * const buffer16 = (uint16_t*)buffer;
for (size_t i = 0; i < size/2; i++)
buffer16[i] = _byteswap_ushort(buffer16[i]);
#elif 1 // assume GCC
uint16_t * const buffer16 = (uint16_t*)buffer;
for (size_t i = 0; i < size/2; i++)
buffer16[i] = __builtin_bswap16(buffer16[i]);
#else
2016-08-10 03:27:59 +00:00
for (size_t i = 0; i < (size & ~1); i += 2)
{
uint8_t tmp = buffer[i + 0];
2016-08-10 03:27:59 +00:00
buffer[i + 0] = buffer[i + 1];
buffer[i + 1] = tmp;
}
2022-07-11 16:42:15 +00:00
#endif
}
2022-07-11 16:42:15 +00:00
void FlipEndian32(uint8_t * const buffer, const size_t size)
{
2022-07-11 16:42:15 +00:00
#ifdef _MSC_VER
uint32_t * const buffer32 = (uint32_t*)buffer;
for (size_t i = 0; i < size/4; i++)
buffer32[i] = _byteswap_ulong(buffer32[i]);
#elif 1 // assume GCC
uint32_t * const buffer32 = (uint32_t*)buffer;
for (size_t i = 0; i < size/4; i++)
buffer32[i] = __builtin_bswap32(buffer32[i]);
#else
for (size_t i = 0; i < (size & ~3); i += 4)
{
uint8_t tmp1 = buffer[i+0];
uint8_t tmp2 = buffer[i+1];
buffer[i+0] = buffer[i+3];
buffer[i+1] = buffer[i+2];
buffer[i+2] = tmp2;
buffer[i+3] = tmp1;
2016-08-10 03:27:59 +00:00
}
2022-07-11 16:42:15 +00:00
#endif
2016-08-10 03:27:59 +00:00
}
} // Util