将Char缓冲区转换为short数组

时间:2011-10-07 19:20:48

标签: c casting char buffer short

我有一个由API函数填充的char *缓冲区。我需要获取该指针所包含的数据,将其转换为unsigned short并将其转换为网络(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();
    }

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

3 个答案:

答案 0 :(得分:0)

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

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

如果数组未终止,那么您需要确定它的确切时间,然后用该值替换strlen(CHAR_ARRAY)

答案 1 :(得分: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中的值。

答案 2 :(得分: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");
}

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