简体   繁体   English

将存储在char中的十六进制/二进制值转换为int - 获得奇怪的结果

[英]Converting hex/binary values stored in char to int - Getting strange results

I am having problems with converting hex/binary values received over socket to an integer. 我在将通过套接字接收的十六进制/二进制值转换为整数时遇到问题。

I am getting the hex value over a socket with the following code: 我使用以下代码在套接字上获取十六进制值:

void get_msg(int sockfd, char *buf)
{
  int n;
  bzero(buf,256);
  n = read(sockfd,buf,255);
  if (n < 0)
    error("ERROR writing socket");
}

I then pass the received binary located in *buf to this function to see them in hex (so that I can check if the calc_msg function below is working properly): 然后我将位于* buf中的接收二进制文件传递给此函数,以十六进制形式查看它们(以便我可以检查下面的calc_msg函数是否正常工作):

void print_msg(char *buf)
{
  int i;
  char *buffer = malloc(4);
  printf("[ ");
  for(i = 0; i < 4; i++) {
    printf("%02x ", ((const unsigned char *) buf)[i] & 0xff);
  }
  printf("]\n");
}

Now, in an attempt to convert the received message to decimal I call this function: 现在,在尝试将收到的消息转换为十进制时,我调用此函数:

void calc_msg(char *buf)
{
  int i;
  int dec[3];
  for(i = 0; i < 4; i++) {
    dec[i] = buf[i];
    printf("Transformation %d: %u\n", i, dec[i]);
  }
}

This function only converts the message sometimes. 此功能有时仅转换消息。 Other times, it give ridiculously high values. 其他时候,它给出了可笑的高价值。 Here is an example output: 这是一个示例输出:

[ 94 cc 78 28 ]
Transformation 0: 4294967188
Transformation 1: 4294967244
Transformation 2: 120
Transformation 3: 40

As you can see, 94 and cc end up being ridiculous values, whereas 78 and 28 convert just fine. 正如你所看到的,94和cc最终是荒谬的价值,而78和28转换得很好。 The only relationship I see is that this only happens for higher values. 我看到的唯一关系是,这只发生在更高的值上。 I have not found any useful information using search engines. 我没有使用搜索引擎找到任何有用的信息。

Thanks! 谢谢! Surculus Surculus

int dec[3]; should be int dec[4]; 应该是int dec[4]; , for starters. , 对于初学者。

Furthermore, this probably happens because all values greater than 127 (assuming an 8-bit char, but this is true in general to any value which doesn't fit into a signed char ) are sign extended during the signed upcast ( char -> int ). 此外,这可能发生,因为所有大于127的值(假设一个8位字符,但对于任何不适合签名char值都是如此)在签名的upcast期间进行符号扩展( char -> int )。 You'd be better off using unsigned char * for your buffers everywhere. 你最好在任何地方使用unsigned char *作为你的缓冲区。

Hex 94 and cc are 148 and 204 in decimal. 十六进制94 and cc是十进制的148和204。 You are trying to store it in a signed char. 您正在尝试将其存储在已签名的字符中。 Which cannot store number more than +127. 其中不能存储超过+127的数字。 This results in being represented as negative value in dec. 这导致在dec中表示为负值。 When you convert to unsigned int gets converted to large values. 当您转换为unsigned int会转换为较大的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM