Reputation: 537
In a server, I get the length of an image data first, then the image data via TCP socket. How can I convert the length (in hexadecimal) to decimal, so that I know how much image data I should read? (eg. 0x00 0x00 0x17 0xF0 to 6128 bytes)
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);
EDITED: This is the working one.
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);
Upvotes: 0
Views: 1419
Reputation: 409404
If you zero-terminate the number, so it becomes a string (assuming you send the digits as characters), you can use strtoul
.
If you send it as a binary 32-bit number, you already have it as you need it. You should just use a different data-type for it: uint32_t
:
uint32_t len;
/* Read the value */
recv(clientSocket, (char *) &len, sizeof(len));
/* Convert from network byte-order */
len = ntohl(len);
When designing a binary protocol you should always use the standard fixed-size data types, like uint32_t
in the example above, and always send all non-textual data in network byte-order. This will make the protocol more portable between platforms. However, you don't have to convert the actual image data as that should already be in a platform-independent format, or just plain data bytes which doesn't have any byte-ordering issues.
Upvotes: 3