我有一个由 API 函数填充的 char * 缓冲区。我需要获取该指针包含的数据,将其转换为无符号短裤并将其转换为网络 (htons()) 格式以通过 UDP 发送。这是我的代码(由于某些原因并非全部)
下面的代码可以工作,但另一端的数据是坏的(不是短裤或网络翻译)
char * pcZap;
while(1)
{
unsigned short *ps;
unsigned short short_buffer[4096];
write_reg(to start xfer);
return_val = get_packet(fd, &pcZap, &uLen, &uLob);
check_size_of_uLen_and_uLob(); //make sure we got a packet
// here I need to chage pcZap to (unsigned short *) and translate to network
sendto(sockFd,pcZap,size,0,(struct sockaddr *)Server_addr,
sizeof(struct sockaddr));
return_val = free_packet(fd, pcZap);
thread_check_for_exit();
}
如有任何帮助,我们将不胜感激。谢谢。
最佳答案
假设您的缓冲区中有 4080 个字节由 16 位样本组成,这意味着您的缓冲区的 4080 字节中总共有 2040 个 16 位样本(16 字节为 header 保留)。因此,您可以执行以下操作:
#define MAXBUFSIZE 4096
#define MAXSHORTSIZE 2040
unsigned char pcZap[MAXBUFSIZE];
unsigned ushort[MAXSHORTSIZE];
//get the value of the returned packed length in uLen, and the header in uLob
unsigned short* ptr = (unsigned short*)(pcZap + uLob);
for (int i=0; i < ((uLen - uLob) / 2); i++)
{
ushort[i] = htons(*ptr++);
}
现在您的 ushort
数组将由 pcZap
数组中的原始值转换而来的网络字节顺序 unsigned short
值组成。然后,当您调用 sendto()
时,请确保使用 ushort
中的值,而不是 pcZap
中的值。
关于将 Char 缓冲区转换为短裤数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7691925/