【问题标题】:Convert hexadecimal from socket to decimal将十六进制从套接字转换为十进制
【发布时间】: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 完全正确。谢谢!

标签: c hex


【解决方案1】:

如果你以零结束数字,所以它变成一个字符串(假设你将数字作为字符发送),你可以使用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,并始终按网络字节顺序发送所有非文本数据。这将使协议在平台之间更具可移植性。但是,您不必转换实际的图像数据,因为它应该已经是独立于平台的格式,或者只是没有任何字节顺序问题的纯数据字节。

【讨论】:

  • 使用网络字节序!当 htonl 将保持架构独立时,我们不要鼓励人们在线上编写 x86 int。
  • @joachim 我无法使其工作...错误 C2664: 'recv' : 无法将参数 2 从 'uint32_t' 转换为 'char *'
  • @boogiedoll 您缺少地址操作符吗?您可能还需要对指针进行类型转换。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-31
  • 2011-07-28
  • 1970-01-01
  • 2018-09-04
相关资源
最近更新 更多