gpt4 book ai didi

c - 如何将 float 转换为无符号变量?

转载 作者:太空宇宙 更新时间:2023-11-04 06:09:51 25 4
gpt4 key购买 nike

有人可以帮我解决浮点变量的字节顺序问题吗?实际上代码在 Solaris 上运行正常,但在 Windows Xp 上运行不正常。这是我的代码的一个示例:....

 int x_snd=1;
float y_snd=1.13;
struct {
int xx_snd;
float yy_snd;
} data_snd;
int x_rec;
float y_rec;
struct {
int xx_rec;
float yy_rec;
} data_rec;

//marshalling
data_snd.xx_snd=htons(x_snd);
data_snd.yy_snd=htonl(*(int*) &y_snd);

//write data to socket
send(sock1, &data_snd, ...

//clean ...

//read data from socket
if recv(sock, &data_rec ...

//unmarshalling
x_rec=ntohs(data_rec.xx_rec);
y_rec= *(float*) &(ntohl(data_rec.yy_rec));

...

代码在 Unix 上用 gcc 编译,在 wndows 上用 MSVC++6 编译。非常感谢您的任何帮助,如果您能指导我找到任何提供有关字节序的有用信息的链接或文档,我将很高兴......

预先感谢您的帮助,

最佳答案

在编码和解码整数时,浮点格式有很多潜在的多样性和问题,而不仅仅是字节序问题。

一种解决方法是使用 printf 将 float 格式化为文本,然后使用 strtof() 读取它们(如 bmargulies 所示)。

只要机器共享相同的 FLT_RADIX 值,另一种方法就是将它们分解为尾数和指数值:

#include <math.h>
#include <limits.h>

float x = 1.13;
int x_exp;
long x_mant;

x_exp = ilogbf(x);
x_mant = (scalbnf(fabsf(x), -x_exp) - 1) * LONG_MAX;
if (x < 0.0)
x_mant = -x_mant;

然后你有一个 int 和一个 long(上面代码中的 x_expx_mant)来放置到电线上,您可以使用普通的 ntohl()htonl() 函数来完成。要将它们转换回 float,请使用:

x = scalbnf((fabsf(x_mant) / LONG_MAX) + 1, x_exp);
if (x_mant < 0)
x = -x;

请注意,大多数机器的 FLT_RADIX 值(在 float.h 中定义)为 2,因此如果您在编译期间检查该值,如果是其他值则中止,你应该是合理便携的。

关于c - 如何将 float 转换为无符号变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1718850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com