I'm swapping bytes in a char buffer:
char* data; // some char buffer
uint16_t* data16 = reinterpret_cast<uint16_t*>(data);
// For debugging:
int align = reinterpret_cast<uintptr_t>(data) % alignof(uint16_t);
std::cout << "aligned? " << align << "\n";
for (size_t i = 0; i < length_of_data16; i++) {
#if defined(__GNUC__) || defined(__clang__)
data16[i] = __builtin_bswap16(data16[i]);
#elif defined(_MSC_VER)
data16[i] = _byteswap_ushort(data16[i]);
#endif
}
I'm casting from char*
to uint16_t*
, which raises a flag because it's casting to a more strictly aligned type.
However, the code runs correctly (on x86), even when the debugging code prints 1 (as in, not aligned). In the assembly I see MOVDQU
, which I take to mean that the compiler recognizes that this might not be aligned.
This looks similar to this question, where the answer was "this is not safe." Does the above code only work on certain architectures and with certain compilers, or is there a subtle difference between these two questions that makes the above code valid?
(Less important: consistent with what I've read online, there's also no noticeable perf difference between aligned and unaligned execution of this code.)