host to network double?

妖精的绣舞 提交于 2019-12-01 03:27:50

问题


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

回答1:


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.




回答2:


Convert it to an agreed string format and send that. Not sure if it's common practice or even decent, but it worked for me (it is true I did not care about performance at that point since I wasn't sending very many values).




回答3:


You might want to look at XDR which was first defined in rfc1014. Obviously, you want to find a library which implements XDR for your platform.



来源:https://stackoverflow.com/questions/6084279/host-to-network-double

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!