Search code examples
ccastingcharbuffershort

Converting Char buffer into an array of shorts


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.


Solution

  • 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:

    #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++);
    }
    

    Now your ushort array will be composed of network-byte-order unsigned short values converted from the original values in the pcZap array. Then, when you call sendto(), make sure to use the values from ushort, not the values from pcZap.