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

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

问题描述

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

How can I serialize doubles and floats in C?

我有以下代码用于序列化 shorts、ints 和 chars.

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;
}

我从这个问题

编辑 2:

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

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天全站免登陆