diff --git a/include/io/read.h b/include/io/read.h index 29b607f..a83a71a 100644 --- a/include/io/read.h +++ b/include/io/read.h @@ -35,6 +35,18 @@ namespace io { return value; } + template <> + float read(std::istream& is) { + union { + uint32_t a; + float b; + } u; + + u.a = read_bytes(is, sizeof(uint32_t)); + + return u.b; + } + template<> size_t read(std::istream& is) { size_t value = 0; diff --git a/include/io/write.h b/include/io/write.h index aa96804..3ed511b 100644 --- a/include/io/write.h +++ b/include/io/write.h @@ -31,6 +31,17 @@ namespace io { write_bytes(os, value, sizeof(T)); } + template <> + void write(std::ostream& os, float value) { + union { + uint32_t a; + float b; + } u; + + u.b = value; + write_bytes(os, u.a, sizeof(uint32_t)); + } + // Special implementation for size_t (also uint64_t, so maybe this is not that smart) template <> void write(std::ostream& os, size_t value) { diff --git a/test/src/test.cpp b/test/src/test.cpp index bb67435..dce3c62 100644 --- a/test/src/test.cpp +++ b/test/src/test.cpp @@ -74,6 +74,24 @@ int main() { return io::read(f) == 80085; }()); + Test("Write for float", [] { + std::fstream f("test.bin", std::ios::trunc | std::ios::in | std::ios::out); + io::write(f, 123.654f); + + bool succes = 4 == f.tellg(); f.seekg(0); char c; + f.read(&c,1); succes &= (c & 0xff) == 0x42; + f.read(&c,1); succes &= (c & 0xff) == 0xf7; + f.read(&c,1); succes &= (c & 0xff) == 0x4e; + f.read(&c,1); succes &= (c & 0xff) == 0xd9; + return succes; + }()); + + Test("Read for float", [] { + std::ifstream f("test.bin"); + return io::read(f) == 123.654f; + }()); + + Test("Write for short size_t", [] { std::fstream f("test.bin", std::ios::trunc | std::ios::in | std::ios::out); io::write(f, 12);