用 C 序列化 double 和 float [英] Serialize double and float with C

查看:27
本文介绍了用 C 序列化 double 和 float的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 C 中序列化双精度和浮点数?

How can I serialize doubles and floats in C?

我有以下用于序列化 short、int 和 char 的代码.

I have the following code for serializing shorts, ints, and chars.

unsigned char * serialize_char(unsigned char *buffer, char value)
{
    buffer[0] = value;
    return buffer + 1;
}

unsigned char * serialize_int(unsigned char *buffer, int value)
{
    buffer[0] = value >> 24;
    buffer[1] = value >> 16;
    buffer[2] = value >> 8;
    buffer[3] = value;
    return buffer + 4;
}

unsigned char * serialize_short(unsigned char *buffer, short value)
{
    buffer[0] = value >> 8;
    buffer[1] = value;
    return buffer + 2;
}

我从 this question

编辑 2:

序列化的目的是将数据发送到UDP套接字,并保证即使字节序不同,也可以在另一台机器上进行反序列化.鉴于我必须序列化 int、double、float 和 char*,是否还有其他最佳实践"来执行此功能?

The purpose of serializing is to send data to a UDP socket and guarantee that it can be deserialized on the other machine even if the endianness is different. Are there any other "best practices" to perform this functionality given that I have to serialize ints, doubles, floats, and char*?

推荐答案

在更新后,您提到数据将使用 UDP 传输并要求最佳实践.我强烈建议将数据作为文本发送,甚至可能添加一些标记 (XML).在传输线上调试与字节序相关的错误是在浪费每个人的时间

Following your update, you mention the data is to be transmitted using UDP and ask for best practices. I would highly recommend sending the data as text, perhaps even with some markup added (XML). Debugging endian-related errors across a transmission-line is a waste of everybody's time

就您问题的最佳实践"部分,我只需 2 美分

Just my 2 cents on the "best practices" part of your question

这篇关于用 C 序列化 double 和 float的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆