0

我的问题有点类似于这个链接中的那个使用 htonl 转换一个 int 数字,并将 memcpy 转换为一个 char*,但什么都没有,还有一些其他类似的问题,但我问一个新问题的原因是因为我没有能够找到解决方案。我想做的是在发送实际消息(sendBuffer)之前将消息的长度从htonl添加为4个字节

int packed_len = strlen(dataInChar);  //dataInChar is the serialized char array
char myByteArray[sizeof(int)];
uint32_t bigEndianValue = htonl(packed_len);  // convert the value to big-endian for cross-platform compatibility
memcpy(myByteArray, &bigEndianValue, sizeof(uint32_t));
std::cout<<"myByteArray length: "<<strlen(myByteArray)<<std::endl;  //output 0

char sendBuffer[1024]; //final buffer to send
memcpy(sendBuffer, &myByteArray, 4);
memcpy(sendBuffer+4, dataInChar, strlen(dataInChar));
std::cout<<"sendBuffer length: "<<strlen(sendBuffer)<<std::endl;  //output 0

我已经好几年没有接触过 C++了,所以请原谅我在这里做错了任何愚蠢的事情。

4

0 回答 0