Skip to content

Commit c967e4d

Browse files
committed
use more bit_cast
Signed-off-by: Rosen Penev <[email protected]>
1 parent 1ea3253 commit c967e4d

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

src/types.cpp

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,6 +314,12 @@ double getDouble(const byte* buf, ByteOrder byteOrder) {
314314
// This algorithm assumes that the internal representation of the double
315315
// type is the 8-byte IEEE 754 binary64 format, which is common but not
316316
// required by the C++ standard.
317+
#ifdef __cpp_lib_bit_cast
318+
uint64_t u;
319+
std::memcpy(&u, buf, sizeof(uint64_t));
320+
u = Image::byteSwap(u, byteOrder == bigEndian);
321+
return std::bit_cast<double>(u);
322+
#else
317323
union {
318324
uint64_t ull_;
319325
double d_;
@@ -331,6 +337,7 @@ double getDouble(const byte* buf, ByteOrder byteOrder) {
331337
static_cast<uint64_t>(buf[6]) << 8 | static_cast<uint64_t>(buf[7]);
332338
}
333339
return u.d_;
340+
#endif
334341
}
335342

336343
size_t us2Data(byte* buf, uint16_t s, ByteOrder byteOrder) {
@@ -395,6 +402,11 @@ size_t d2Data(byte* buf, double d, ByteOrder byteOrder) {
395402
// This algorithm assumes that the internal representation of the double
396403
// type is the 8-byte IEEE 754 binary64 format, which is common but not
397404
// required by the C++ standard.
405+
#ifdef __cpp_lib_bit_cast
406+
auto u = Image::byteSwap(std::bit_cast<uint64_t>(d), byteOrder == bigEndian);
407+
std::memcpy(buf, &u, sizeof(u));
408+
return sizeof(u);
409+
#else
398410
union {
399411
uint64_t ull_;
400412
double d_;
@@ -421,6 +433,7 @@ size_t d2Data(byte* buf, double d, ByteOrder byteOrder) {
421433
buf[7] = static_cast<byte>(u.ull_ & m);
422434
}
423435
return 8;
436+
#endif
424437
}
425438

426439
void hexdump(std::ostream& os, const byte* buf, size_t len, size_t offset) {

0 commit comments

Comments
 (0)