1

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();
    }

どんな助けでも大歓迎です。ありがとうございました。

4

3 に答える 3

0

文字の配列がヌルで終了している場合は、次のように簡単に実行できます。

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

配列が null で終了していない場合は、配列の長さを正確に把握してからstrlen(CHAR_ARRAY)、その値に置き換える必要があります。

于 2011-10-07T19:37:30.760 に答える
0

バッファに 16 ビット サンプルで構成される 4080 バイトがあると仮定すると、バッファの 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 shortpcZapsendto()ushortpcZap

于 2011-10-07T19:44:26.110 に答える
0

ホスト エンディアンの short int を表すバイトのチャンクをネットワーク エンディアンに変換するだけでよい場合は、次のようにします。

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 に答える