Home > Software design >  Convert Hex to Decimal from char array
Convert Hex to Decimal from char array

Time:04-20

I have a CHAR buffer That contains some hex value first of all i want to concatenate every 2 successive elements of the array then convert it to Decimal for example i have recvbuf[i] = d and recvbuf[i 1] = 60 >>> recvbuf[i] = d60 (hex value) >>> recvbuf[i] =3424 (in decimal)

i started with this :

recvbuf[i]=recvbuf[i]&recvbuf[i 1];

can you help convert recvbuf[i] to Decimal value please

CodePudding user response:

While your question lacks some information, I try to provide an answer for what I have understood.

#include <stdio.h>
#include <stdint.h>

#define NUM_VALUES 5
int main(void)
{
  uint8_t input_data[NUM_VALUES * 2] = {1, 2, 0x0d, 0x60, 5, 6, 7, 8, 9, 10};
  uint16_t result_data[NUM_VALUES];

  for (int i = 0; i < NUM_VALUES; i  )
  {
    result_data[i] = (uint16_t)input_data[2*i] << 8 | input_data[2*i 1];
    printf("result[%d] = 0xx == %5u\n", i, result_data[i], result_data[i]);
  }
}

Output:

~/tests$ ./test
result[0] = 0x0102 ==   258
result[1] = 0x0d60 ==  3424
result[2] = 0x0506 ==  1286
result[3] = 0x0708 ==  1800
result[4] = 0x090a ==  2314

As you can see, hex and decimal are only representation of the same value.

  • Related