将ASCII反序列化为结构
de-serialize ASCII to struct
如果要从网络接收消息,我会想出以下结构来声明各种格式:
#include <stdint.h>
#include <iostream>
#include <string.h>
template<int T>
struct uint
{
static uint<T> create(uint64_t value)
{
uint<T> r = {value};
return r;
}
uint(uint64_t value)
{
v = value;
}
uint()
{}
uint<T>& operator =(uint64_t value)
{
v = value;
return *this;
}
operator uint64_t() const
{
return (uint64_t)v;
}
unsigned long long v:T;
}__attribute__((packed));
示例:
typedef uint<5> second_t;
假设其中一种消息格式(通过某些过程自动生成)如下:
struct seconds
{
char _type;
second_t _second;
} __attribute__((packed));
现在假设我想使用字符串填充上面messahe的一个实例:
int main()
{
seconds ii;
const char *i = "123456";
// memset, memcpy,sprintf... ??? what to use here?
std::cout << ii._type << " " << ii._second << std::endl;
}
给定流123456
,我期望seconds
(ii
)结构的实例具有char
ii._type
="1"和整数ii._second
=23456。但我不知道该怎么做。你知道我该怎么做吗?你对如何改进基本结构有什么建议吗?
感谢
您有许多更简单、更可靠的选项,几乎不需要任何工作。
查看谷歌协议缓冲区(独立于平台的消息序列化和去序列化):https://developers.google.com/protocol-buffers/
或boost::序列化-(可能更快,但不是独立于平台)http://www.boost.org/doc/libs/1_58_0/libs/serialization/doc/index.html
相关文章:
- 如何知道QDataStream不能反序列化某些内容
- 增强基于 XML class_id的反序列化
- 提升反序列化对象具有 nan 或 -nan 值
- 如何在 c++ 非托管代码中反序列化 byte[] 的 json 字符串?
- 如何反序列化数组?
- Protobuf中重复字段的问题.使用重复字段进行序列化/反序列化的更好方法是什么?
- 通过 tcp 发送 C# 类并在 C++ 上反序列化
- 序列化和反序列化boost共享指针
- 在C++中使用POCO和grain对多个对象进行反序列化
- C++中整数向量的序列化/反序列化
- 使用 Json 转换器反序列化 WCF 服务中的C++字符串
- 使用 QDataStream 对原始数据进行反序列化
- 使用协议缓冲区创建通用反序列化程序
- 如何在C++中从头开始反序列化文件(没有库)
- 在协议缓冲区 c++ 中反序列化字符串数组
- 在进程的内存中序列化/反序列化
- 如何从平面缓冲区中反序列化联合结构的 void* 值的大小
- 使用Boost,如何在类层次结构改变后反序列化c++类
- Boost Fusion和Boost property_tree用于结构的反序列化
- 序列化和反序列化套接字中的结构