0

I'm new to C development. How can convert I double values to a uint_8 type array.

double test=1234.642462

I want to save as it as

uint8_t data[] = {'1','2','3','4','.','6','4','2','4','6','2'};

Any help is appreciated. Thank you.

Ven Varu
  • 33
  • 4

2 Answers2

1

You can use the snprintf function like this:

#include <stdlib.h>    

int8_t data[20];
double test=1234.642462;

snprintf(data, 20, "%f", test);

The 20 character limit should be adjusted to the desired precision, since floating point numbers can be very long.

tversteeg
  • 4,717
  • 10
  • 42
  • 77
0

DBL_MAX is typically about 179769...(303 more digits).0. Usually only the first 17 are consider significant.

DBL_MIN is typically about 0.000(303 more zeros)222507... And again usually only the first 17 are consider significant.

To convert the entire range of double into a non-exponential decimal string showing significant digits can take hundreds of bytes - not a practical approach.

To convert a double into a decimal text representation, stored in char, uint8_t, int8_t, etc., is best done using exponential notation with enough, but not excessive amount of significant digits. Use *printf() family with e.

#include <float.h>
//                     -   d   .       dddd                e   -  expo \0
#define DBL_TEXT_SIZE (1 + 1 + 1 + (DBL_DECIMAL_DIG - 1) + 1 + 1 + 6 + 1)
...
uint8_t data[DBL_TEXT_SIZE];
sprintf(data, "%.e", DBL_DECIMAL_DIG - 1, test);

For more details: See Printf width specifier to maintain precision of floating-point value

Community
  • 1
  • 1
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256