-1

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.

5
  • Use snprintf. Commented Sep 13, 2016 at 13:41
  • 3
    Convert it to a string, then convert the string to uint8_t. Commented Sep 13, 2016 at 13:42
  • sprintf(data, "%f", test); Commented Sep 13, 2016 at 13:42
  • 1
    You want a C-string or just as array? Commented Sep 13, 2016 at 13:43
  • 2
    Do you want the result as int8_t or uint8_t? Because your question mentions both. Commented Sep 13, 2016 at 13:51

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.