I have raw binary data blocks (actually, CBOR-encoded). To read numeric I use common form like:
template <typename T> // T can be uint64_t, double, uint32_t, etc...
auto read(const uint8_t *ptr) -> T {
return *((T *)(ptr)); // all endianess-aware functions will be performed later
}
This solution works on x86/x86_64 PC and arm/arm64 iOS.
But, on arm/armv7 Android with clang compiler on default release optimization level (-Os) i receive SIGBUS with code 1 (unaligned read) for types, larger then one byte. I fix that problem with another solution:
template <typename T>
auto read(const uint8_t *ptr) -> T {
union {
uint8_t buf[sizeof(T)];
T value;
} u;
memcpy(u.buf, ptr, sizeof(T));
return u.value;
}
Is there any platform-independent solution, that will not impact performance?