Is there need to convert byte order for strings?

假装没事ソ 提交于 2019-12-23 23:06:55

问题


Is there need to convert to network/host byte ordering when sending and receiving strings. The available functions (such as htons()) only work with 16 and 32 bit integers. I also know for a fact that a single char shouldn't make a difference, as generally, it is a byte large. However what about strings ?

The following is a code snippet

 int len; recv(fd, &len, sizeof (int), 0); 
 len = ntohl(len);

 char* string = malloc(sizeof (char) * (len + 1)); 
 int received = recv(fd, string, sizeof (char) * len, 0); 
 string[len] = '\0';

回答1:


It depends on the encoding of the string.

If it's a byte-oriented format (plain old ASCII or UTF-8), then it doesn't matter.

If it uses "code points" larger than a single byte, then yes it matters.




回答2:


C strings are simply an array of one byte values with a convention of a one byte special value to terminate them, thus there is nothing to swap. Shorts and ints are multiple byte values which get stored differently according to the hardware requirements, thus the need to normalize their storage order across the network (in case the receiver has a different hardware architecture).



来源:https://stackoverflow.com/questions/15877643/is-there-need-to-convert-byte-order-for-strings

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