2013-03-05 180 views
0

在服務器中,首先獲取圖像數據的長度,然後通過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); 
+1

「二進制十六進制數據」是什麼意思?它可以是二進制或十六進制。你在尋找類似'ntohl'的東西嗎? **將這4個字節寫入流的代碼在哪裏? – Jon 2013-03-05 11:42:46

+0

@Jon。謝謝! – askingtoomuch 2013-03-05 12:43:37

回答

3

如果零終止的數量,因此它成爲一個字符串(假設你發送的數字作爲字符),你可以使用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,始終將所有非 - 網絡字節順序的文本數據。這將使協議在平臺之間更加便攜。但是,您不必將實際圖像數據轉換爲應該已經處於獨立於平臺的格式,或者只是沒有任何字節排序問題的普通數據字節。

+5

使用網絡端!我們不要鼓勵人們在網絡上寫x86嵌入式時,htonl會讓架構獨立。 – 2013-03-05 11:54:39

+0

@joachim我無法使它工作...錯誤C2664:'recv':無法將參數2從'uint32_t'轉換爲'char *' – askingtoomuch 2013-03-05 12:31:05

+0

@boogiedoll您錯過了操作符的地址?您還可能需要鍵入指針。 – 2013-03-05 12:32:55

相關問題