1

我有一个由 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();
    }

任何帮助,将不胜感激。谢谢你。

4

3 回答 3

0

如果您的字符数组为空终止,那么您可以简单地执行以下操作:

for (int i=0; i<strlen(CHAR_ARRAY); i++)
     short_buffer[i] = (unsigned short) CHAR_ARRAY[i];

如果数组不是以空值终止的,那么您需要弄清楚它到底有多长,然后strlen(CHAR_ARRAY)用该值替换。

于 2011-10-07T19:37:30.760 回答
0

假设您的缓冲区中有 4080 个字节由 16 位样本组成,这意味着您的 4080 个字节中有 2040 个 16 位样本(为标题保留 16 个字节)。因此,您可以执行以下操作:

#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数组将由从数组unsigned short中的原始值转换而来的网络字节顺序值pcZap组成。然后,当您调用 时sendto(),请确保使用来自 的值ushort,而不是来自 的值pcZap

于 2011-10-07T19:44:26.110 回答
0

如果您需要做的只是将一大块字节(将主机端序中的短整数表示为网络端序),您可以这样做:

size_t i;
size_t len = uLen - 16 - uLob;
size_t offset = uLob + 16;

if(len % 2 != 0) {
  ..error not a multiple of 16 bit shorts...
}
//now, if you're on a little endian host (assuming the shorts in 
//pcZap is laid out as the host endian...), just swap around the bytes
//to convert the shorts to network endian.
for(i = 0; i < len; i+=2) {
    //swap(&pcZap[offset + i],&pcZap[offset + i + 1]);
    char tmp = pcZap[offset + i];
    pcZap[offset + i] =  pcZap[offset + i + 1]; 
    pcZap[offset + i + 1] = tmp;
}
//if you're on a big endian host, forget the above loop, the data
//is already in big/network endian layout.

//and just send the data.
if(sendto(sockFd,pcZap + offset,len,0,(struct sockaddr *)&Server_addr,
               sizeof Server_addr) == -1) {
   perror("sendto");
}

请注意,您的代码sizeof(struct sockaddr)在 sendto() 调用中有错误,您希望它是 Server_addr 的实际大小。

于 2011-10-07T19:58:44.640 回答