[英]Convert hexadecimal from socket to decimal
在服務器中,我首先獲取圖像數據的長度,然后通過TCP套接字獲取圖像數據的長度。 如何將長度(十六進制)轉換為十進制,以便知道應該讀取多少圖像數據? (例如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);
如果您將數字用零結尾,那么它就變成了字符串(假設您將數字作為字符發送),可以使用strtoul
。
如果將其作為32位二進制數發送,則已經可以根據需要獲取它了。 您應該為此使用其他數據類型: uint32_t
:
uint32_t len;
/* Read the value */
recv(clientSocket, (char *) &len, sizeof(len));
/* Convert from network byte-order */
len = ntohl(len);
設計二進制協議時,應始終使用標准的固定大小的數據類型,例如上述示例中的uint32_t
,並始終以網絡字節順序發送所有非文本數據。 這將使協議在平台之間更加可移植。 但是,您不必轉換實際的圖像數據,因為它應該已經是與平台無關的格式,或者只是沒有字節順序問題的普通數據字節。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.