0

サーバーでは、最初に画像データの長さを取得し、次に TCP ソケットを介して画像データを取得します。長さ (16 進数) を 10 進数に変換して、読み取る必要がある画像データの量を知るにはどうすればよいですか? (例: 0x00 0x00 0x17 0xF0 ~ 6128 バイト)

char len[4];
char buf[1024];
int lengthbytes = 0;
int databytes = 0;
int readbytes = 0;

// receive the length of image data
lengthbytes = recv(clientSocket, len, sizeof(len), 0);

// how to convert binary hex data to length in bytes

// get all image data 
while ( readbytes < ??? ) {

    databytes = recv(clientSocket, buf, sizeof(buf), 0);

    FILE *pFile;
    pFile = fopen("image.jpg","wb");
    fwrite(buf, 1, sizeof(buf), pFile);

    readbytes += databytes;
}

fclose(pFile);  

編集済み:これは作業中のものです。

typedef unsigned __int32 uint32_t; // Required as I'm using Visual Studio 2005
uint32_t len;
char buf[1024];
int lengthbytes = 0;
int databytes = 0;
int readbytes = 0;

FILE *pFile;
pFile = fopen("new.jpg","wb");

// receive the length of image data
lengthbytes = recv(clientSocket, (char *)&len, sizeof(len), 0);

// using networkd endians to convert hexadecimal data to length in bytes
len = ntohl(len);

// get all image data 
while ( readbytes < len ) {
databytes = recv(clientSocket, buf, sizeof(buf), 0);
fwrite(buf, 1, sizeof(buf), pFile);
readbytes += databytes;
}

fclose(pFile);  
4

1 に答える 1

3

数値をゼロで終了して文字列になる場合(数字を文字として送信すると仮定)、を使用できますstrtoul


32ビットの2進数として送信する場合は、必要に応じてすでに持っています。別のデータ型を使用する必要がありますuint32_t::

uint32_t len;

/* Read the value */
recv(clientSocket, (char *) &len, sizeof(len));

/* Convert from network byte-order */
len = ntohl(len);

バイナリプロトコルを設計するときは、上記の例のように、常に標準の固定サイズのデータ​​型を使用し、uint32_tすべての非テキストデータを常にネットワークバイトオーダーで送信する必要があります。これにより、プロトコルがプラットフォーム間でより移植性が高くなります。ただし、実際の画像データはすでにプラットフォームに依存しない形式である必要があるため、変換する必要はありません。または、バイト順序の問題がない単なるデータバイトです。

于 2013-03-05T11:40:57.393 に答える