我想通过 unix 中的 tcp 套接字发送字符数组。
我的第一个想法是使用普通的 char 数组作为将通过套接字发送的结构:
typedef struct __attribute__((packed))
{
uint8_t type;
uint8_t id_index;
char char_value[STR_MSG_MAX];
} a_msg;
Run Code Online (Sandbox Code Playgroud)
很简单,因为 C 字符总是 8 位长。然而,经过一番谷歌搜索后,我发现即使 char 总是 8 位长,底层表示实际上也可能是 32 位整数。所以我的印象是 char 可能不是在消息中表示字符串的最佳方式,该消息将通过套接字从 FreeBSd 发送到 Linux(或者如果您想输入一些其他 unix =)...)。
stdint.h 存在于当今所有现代 UNIX 上(我希望),我的想法是,也许 uint8_t 或 int8_t 数组可以解决这个问题。
typedef struct __attribute__((packed))
{
uint8_t type;
uint8_t id_index;
uint8_t char_value[STR_MSG_MAX];
} a_msg;
Run Code Online (Sandbox Code Playgroud)
或者
typedef struct __attribute__((packed))
{
uint8_t type;
uint8_t id_index;
int8_t char_value[STR_MSG_MAX];
} a_msg;
Run Code Online (Sandbox Code Playgroud)
但是,uint8_t 是无符号字符,int8_t 是有符号字符。标准 C 字符都不是,因为据我了解,实现是未定义的。
我的问题是:用 C 表示字符数组(字符串)的最佳方式是什么,该数组将以 *nix(Linux、FreeBSD 等)平台无关的方式通过 tcp/ip 发送。
尽管char可能超过 8 位宽,但它必须始终是(相等)最窄的类型。(因为除其他原因外,sizeof(char)被定义为 1)。
因此,如果平台提供int8_t,则char也必须恰好为 8 位(因为char单独限制为至少 8 位)。这意味着您不妨使用char.
| 归档时间: |
|
| 查看次数: |
7334 次 |
| 最近记录: |