如何将字符数组转换为 uint8_t

fat*_*ror 3 c casting send recv uint8t

我正在开发一个服务器-客户端应用程序,它基本上模拟了一个聊天室。这是学校的作业,协议规范有些严格。

我有一个字符数组,它将存储来自客户端的所有消息。

客户端必须首先将消息的长度作为 uint8_t 发送,然后将消息本身作为字符数组发送。

我的问题是我需要存储在发送实际消息之前发送的 uint8_t 值,但我只能使用消息数组来存储来自客户端的任何信息。

如果我没记错的话,char 数组不会存储发送过来的 uint8_t,除非我以某种方式投射它。

如何将 uint8_t 转换为字符并返回到 uint8_t?

我试过在这里寻找类似的问题,但找不到一个例子。

服务器.c

char msg[100];
recv(clients_sd, msg, sizeof(msg), 0);
uint8_t len; /* store the length of the message here */
char message_received[len];
recv(clients_sd, message_received, sizeof(message_received), 0); /* get and store the message here */
Run Code Online (Sandbox Code Playgroud)

客户端

uint8_t length = 21;
char clients_message[] = "Hi how are you today?";
send(servers_sd, &length, sizeof(length), 0);
send(serers_sd, &clients_message, sizeof(clients_message), 0);
Run Code Online (Sandbox Code Playgroud)

PSk*_*cik 5

如果您使用的uint8_t是 a typedefto unsigned char(您很可能是)的架构,那么只需取第一个char并将其转换为uint8_t

length = (uint8_t)(message_received[0]);
Run Code Online (Sandbox Code Playgroud)

它应该工作。