将 Char 缓冲区转换为 Shorts 数组
我有一个 char * 缓冲区,由 API 函数填充。我需要获取该指针包含的数据,将其转换为无符号短裤并将其转换为网络 (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();
}
任何帮助将不胜感激。谢谢。
I have a char * buffer that is filled by an API function. I need to take the data that is contained with that pointer, cast it to unsigned shorts and translate it into network (htons()) format to send it over UDP. Here is my code (not all though for a few reasons)
The code below will work but that data on the other side is bad (not shorts or network translated)
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();
}
Any help would be appreciated. Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设缓冲区中有 4080 个字节由 16 位样本组成,这意味着缓冲区的 4080 个字节中总共有 2040 个 16 位样本(16 个字节保留给标头)。因此,您可以执行以下操作:
现在您的
ushort
数组将由从pcZap
中的原始值转换而来的网络字节顺序unsigned Short
值组成代码>数组。然后,当您调用sendto()
时,请确保使用ushort
中的值,而不是pcZap
中的值。Assuming you have 4080 bytes in your buffer that are composed of 16-bit samples, that would mean you have 2040 total 16-bit samples in the 4080 bytes of your buffer (16-bytes are reserved for the header). Therefore you can do the following:
Now your
ushort
array will be composed of network-byte-orderunsigned short
values converted from the original values in thepcZap
array. Then, when you callsendto()
, make sure to use the values fromushort
, not the values frompcZap
.如果您的字符数组以 null 结尾,那么您可以简单地执行以下操作:
如果数组不是以 null 结尾,那么您需要计算出它到底有多长,然后将
strlen(CHAR_ARRAY)
替换为那个值。If your array of chars is null terminated then you can simply do:
If the array isn't null terminated then you'll need to figure out how long it is exactly and then replace
strlen(CHAR_ARRAY)
with that value.如果您需要做的只是将表示主机字节序中的短整数的字节块转换为网络字节序,则可以执行以下操作:
请注意,您的代码在 sendto() 调用中有
sizeof(struct sockaddr)
,这是错误的,您希望它是 Server_addr 的实际大小。If all you need to do is convert a chunk of bytes, representing short ints in host endian to network endian, you do this:
Note that your code had
sizeof(struct sockaddr)
in the sendto() call, which is wrong, you want it to be the actual size of Server_addr.