简体   繁体   中英

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):

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. 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

int dec[3]; should be 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 ). You'd be better off using unsigned char * for your buffers everywhere.

Hex 94 and cc are 148 and 204 in decimal. You are trying to store it in a signed char. Which cannot store number more than +127. This results in being represented as negative value in dec. When you convert to unsigned int gets converted to large values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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