From 8246c5b5dd9c35124bbf88538c8b75e748adb9c9 Mon Sep 17 00:00:00 2001 From: Ahmet Inan Date: Wed, 30 Jul 2025 08:23:44 +0200 Subject: [PATCH] added int to float and float to int helpers --- wav.hh | 29 ++++++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/wav.hh b/wav.hh index 4b33552..94c8e95 100644 --- a/wav.hh +++ b/wav.hh @@ -35,6 +35,15 @@ class ReadWAV : public ReadPCM return true; return false; } + static float int2float(int value) + { + union { + int i; + float f; + } u; + u.i = value; + return u.f; + } public: ReadWAV(const char *name) : is(name, std::ios::binary) { @@ -123,12 +132,10 @@ public: stride = channels_; for (int n = 0; n < num; ++n) { for (int c = 0; c < channels_; ++c) { - if (bytes == 4) { - int v = readLE(4); - buf[stride * n + c] = *reinterpret_cast(&v); - } else { + if (bytes == 4) + buf[stride * n + c] = int2float(readLE(4)); + else buf[stride * n + c] = TYPE(readLE(bytes) - offset) / TYPE(factor); - } } } } @@ -169,6 +176,15 @@ class WriteWAV : public WritePCM for (int i = 0; i < b; ++i) os.put(255 & (v >> (8 * i))); } + static int float2int(float value) + { + union { + float f; + int i; + } u; + u.f = value; + return u.i; + } public: WriteWAV(const char *name, int rate, int bits, int channels) : os(name, std::ios::binary | std::ios::trunc), @@ -242,8 +258,7 @@ public: for (int n = 0; n < num; ++n) { for (int c = 0; c < channels_; ++c) { if (bytes == 4) { - float v = buf[stride * n + c]; - writeLE(*reinterpret_cast(&v), 4); + writeLE(float2int(buf[stride * n + c]), 4); } else { TYPE v = TYPE(offset) + TYPE(factor) * buf[stride * n + c]; writeLE(std::nearbyint(std::min(std::max(v, TYPE(min)), TYPE(max))), bytes);