问题描述
我想通过网络发送一些双precision浮点数。 (标准C,标准插座)没有htond或ntohd将数据转换和从网络字节顺序。我该怎么办?我在我的头上一对夫妇的解决方案,但我想知道常见的做法是什么。
(我也想知道什么是发送64位整数,像GStreamer的使用gint64值普遍的做法)
编辑:
这是一个解决方案我想到的。我presume它适用于任何规模大小的整数,但它是正确的双打?
无效swap_if_necessary(void *的BUFF,INT buff_len)
{
uint32_t的富= 1;
如果(htonl(富)!=富)
{
字符* to_swap =(字符*)的buff; INT I;
对于(i = 0; I< buff_len / 2;我++)
{
焦炭swap_buff = to_swap [I]
to_swap [I] = to_swap [buff_len -1 -i]
to_swap [buff_len -1 -i] = swap_buff;
}
}
}
什么安德烈的意思是,二进制浮点数是因为不同的计算机体系结构之间的差异不能跨网络值得信赖。差异超出的字节顺序(大/小端)。像转换为字符串或使用库如XDR的事情。因此,确实是必要的,如果有你的数据将是由不同的计算机体系结构处理的任何机会。
整数和字符的简单格式可以漏网之鱼只有尾数调整,但浮点变得更加复杂。
I'd like to send some double precision floating point numbers over the network. (standard C, standard sockets) There is no htond or ntohd to convert the data to and from network byte order. What should I do? I have a couple solutions in my head but I'd like to know what the common practice is.
(I'd also like to know what is the common practice for sending 64bit ints, like gint64 values used by gstreamer)
edit:This is one solution I thought of. I presume it works for any size integers, but is it correct for doubles?
void swap_if_necessary (void* buff, int buff_len)
{
uint32_t foo = 1;
if ( htonl(foo) != foo )
{
char* to_swap = (char*)buff;
int i;
for (i = 0; i < buff_len/2; i++)
{
char swap_buff = to_swap[i];
to_swap[i] = to_swap[buff_len -1 -i];
to_swap[buff_len -1 -i] = swap_buff;
}
}
}
What Andre is saying is that binary floating point numbers are not trustworthy across networks because of differences between different computer architectures. Differences that go beyond byte order (big/little endian). Thus things like converting to strings or use of libraries such as XDR, is really necessary if there is any chance your data is going to be processed by different computer architectures.
The simple formats of integers and characters can slip through with just endian adjustments but floating point gets more complex.
这篇关于举办网络双?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!