建议参考Protobuf
转换的思路就是用memcpy
需要用到头文件cstdint,里面规定了标准固定长度的整数类型
浮点类型并没有固定长度的说法,但是float一般是32位,double一般是64位
固定长度的整数类型:[u/None]int[Length]_t,比如uint8_t/int64_t
// Bytes.h #ifndef Zhonghui_BYTES_H #define Zhonghui_BYTES_H #include<algorithm> #include<cstdint> #include<cstring> #include<vector> typedef uint8_t Byte; class Bytes { public: Bytes()=default; ~Bytes()=default; protected: std::vector<Byte> m_data; public: void from_uint32(uint32_t value) { m_data.resize(4); memcpy(m_data.data(),&value,sizeof(uint32_t)); } static Bytes uint32(uint32_t value) { Bytes Res; Res.from_uint32(value); return Res; } uint32_t to_uint32() const { if(m_data.size()!=4) return 0; uint32_t Res; memcpy(&Res,m_data.data(),sizeof(uint32_t)); return Res; } void from_int32(int32_t value) { m_data.resize(4); memcpy(m_data.data(),&value,sizeof(int32_t)); } static Bytes int32(int32_t value) { Bytes Res; Res.from_int32(value); return Res; } int32_t to_int32() const { if(m_data.size()!=4) return 0; int32_t Res; memcpy(&Res,m_data.data(),sizeof(int32_t)); return Res; } void from_float32(float value) { m_data.resize(4); memcpy(m_data.data(),&value,sizeof(float)); } static Bytes float32(float value) { Bytes Res; Res.from_float32(value); return Res; } float to_float32() const { if(m_data.size()!=4) return 0.0f; float Res; memcpy(&Res,m_data.data(),sizeof(float)); return Res; } //Add Others public: const Byte* GetBytesPtr() const { return m_data.data(); } void Clear() { m_data.clear(); } Bytes Range(int start,int length) const { Bytes Res; int limit=start+std::min(length,static_cast<int>(m_data.size())); for(int i=start;i<limit;i+=1) { Res.m_data.push_back(m_data[i]); } return Res; } void Append(const Bytes& rhx) { for(auto i=rhx.m_data.begin();i!=rhx.m_data.end();++i) { m_data.push_back(*i); } } int Length() const { return static_cast<int>(m_data.size()); } public: static bool Check() { if(sizeof(float)!=4) return false; if(sizeof(double)!=8) return false; return true; } }; #endif