0

I am having issues converting hexadecimal bytes to int so as to calculate the sum.

I have this hexadecimal bytes in a char array but I am having issues converting them to decimal(int) and summing all of them. here is some lines of code:

int main() {

  char recv[4] = {0x00, 0x03, 0x9e, 0x40};

  int d1 = recv[0] * 256;
  int d2 = recv[1] * 256;
  int d3 = recv[2] * 256;
  int d4 = recv[3] * 1;

  int dt = d1 + d2 + d3 + d4; 

  printf("d1: %d\n", d1);
  printf("d2: %d\n", d2);
  printf("d3: %d\n", d3);
  printf("d4: %d\n", d4);

  printf("sum is: %d\n", dt);


  return 0;

This is the result I am getting:

d1: 0
d2: 768
d3: -25088
d4: 64
sum is: -24256
steinacoz
  • 28
  • 4

1 Answers1

0
#include <stdio.h>

int main(void)
{
    char recv[4] = {0x00, 0x03, 0x9e, 0x40};
    unsigned int result;

    result = ((unsigned char)recv[0] << 24) | 
             ((unsigned char)recv[1] << 16) |
             ((unsigned char)recv[2] <<  8) |
             ((unsigned char)recv[3] <<  0);

    printf("0x%08X\n", result);

    return 0;
}

Output

(link)

Success #stdin #stdout 0s 4568KB
0x00039E40
abelenky
  • 63,815
  • 23
  • 109
  • 159