hobik
hobik

Reputation: 501

Hex To Double Converting in C

I am trying to convert hex value to double value and I am using below codes:

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

double HexToDoubleConverter(uint8_t *hexArray);
uint8_t dummyArray[10] = {0xb2 , 0x9c,  0x9b, 0x6e, 0xcd,  0x8f, 0x44,  0x40}; 

int main()
{
    printf("convertedValue : %f",HexToDoubleConverter((uint8_t *)&dummyArray) );

    return 0;
}


double HexToDoubleConverter(uint8_t *hexArray)
{
   uint64_t convertedValue = 0;
   uint8_t j;
   for (j = 0; j < 8; j++)
  {
   convertedValue += ((char*)&hexArray)[j]; 
  }  

  return (*((double*)&convertedValue));
}

And also I tried like this:

   for (j = 0; j < 8; j++)
  {
   convertedValue |= (hexArray[j] << (8 * j)); 
  }  

But I get :convertedValue : 0.000000 But I expected 41.123456789

How can I solve this where is my mistake ?

Upvotes: 0

Views: 252

Answers (1)

0___________
0___________

Reputation: 67820

This array contains the byte representation of the double number. You need to simply copy it into the double variable.

uint8_t dummyArray[10] = {0xb2 , 0x9c,  0x9b, 0x6e, 0xcd,  0x8f, 0x44,  0x40}; 

int main()
{
    double x;

    memcpy(&x,dummyArray, sizeof(x));
    printf("convertedValue : %f\n",x );

    return 0;
}

https://godbolt.org/z/dP5nnWbb5

Do not worry about 'memcpy' call. This function is well known to the compiler and most of the compilers will replace it with simple assembly instructions

Upvotes: 2

Related Questions