【发布时间】:2013-02-19 19:08:53
【问题描述】:
在服务器中,我首先获取图像数据的长度,然后通过 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);
【问题讨论】:
-
“二进制十六进制数据”是什么意思?它是二进制或十六进制。你在寻找类似
ntohl的东西吗?将这 4 个字节写入到流中的代码在哪里? -
@Jon 完全正确。谢谢!