// Represent // // Douglas Thrift // // $Id$ #include #include #include #include class Binary { private: std::vector bytes; public: Binary(std::string& string, bool signed_ = false); template Binary(const Type& type); template Type convert(bool signed_ = false); operator std::string() const; }; Binary::Binary(std::string& string, bool signed_) : bytes(string.size() / 8, 0) { std::string::size_type off(string.size() % 8); if (off != 0) { bytes.push_back(0); string.insert(0, 8 - off, signed_ && string[0] == '1' ? '1' : '0'); } std::string::size_type index(0); _rmforeach (std::vector, byte, bytes) { _rfor (char, bit, 0, 8) { *byte |= (string[index++] == '1') << bit; } } } template Binary::Binary(const Type& type) : bytes(sizeof (type)) { char* type_(reinterpret_cast(const_cast(&type))); _mforeach (std::vector, byte, bytes) *byte = *type_++; } template Type Binary::convert(bool signed_) { Type type; if (sizeof (type) != bytes.size()) bytes.resize(sizeof (type), signed_ && bytes.back() >> 7 ? ~0 : 0); char* type_(reinterpret_cast(&type)); _foreach (std::vector, byte, bytes) *type_++ = *byte; return type; } Binary::operator std::string() const { std::string string; _rforeach (std::vector, byte, bytes) _rfor (char, bit, 0, 8) string +=1 & *byte >> bit ? '1' : '0'; return string; } inline std::ostream& operator<<(std::ostream& out, const Binary& binary) { return out << std::string(binary); } int main(int argc, char* argv[]) { std::string hello("Hello, World!"); _foreach (std::string, atom, hello) { std::cout << Binary(*atom) << " = " << *atom << std::endl; } _fori (index, -10, 11) { std::cout << Binary(index) << " = " << index << std::endl; } _foru (index, -10, 11) { std::cout << Binary(index) << " = " << index << std::endl; } for (float index(-1.0); index < 1.0; index += 0.1) { std::cout << Binary(index) << " = " << index << std::endl; } for (double index(-1.0); index < 1.0; index += 0.1) { std::cout << Binary(index) << " = " << index << std::endl; } std::string string("101001101001"); Binary binary(string, true); std::cout << binary << " = " << string << std::endl; float value(binary.convert()); std::cout << binary << " = " << value << std::endl << Binary(value) << " = " << value << std::endl; return 0; }