是否需要转换字符串的字节顺序? [英] Is there need to convert byte order for strings?

查看:122
本文介绍了是否需要转换字符串的字节顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在发送和接收字符串时是否需要转换为网络/主机字节顺序。可用函数(例如htons())仅适用于16位和32位整数。我也知道一个字符不起作用,因为通常这是一个字节大。但是字符串呢?

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 ?

以下是代码段

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


推荐答案

这取决于字符串的编码。

It depends on the encoding of the string.

如果是面向字节的格式(普通的ASCII或UTF-8),那就没关系了。

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.

这篇关于是否需要转换字符串的字节顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆