Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert double value to a char array in C

How do I convert double value to a char array in C?

double a=2.132;
char arr[8];

Is there any way to do this in standard C? Can anyone give any solution?

like image 879
Hashan Avatar asked Sep 18 '11 15:09

Hashan


People also ask

How do I convert a double to a char?

A double cannot be converted to a char*. If you're simply trying to get a string representation of the double, you're going to have to convert it to a char array. A function accepting a char* will accept a char[].

How do I convert a char to a double in C++?

We can convert a char array to double by using the std::atof() function.


2 Answers

If you are about to store the double DATA, not the readable representation, then:

#include <string.h>

double a=2.132;
char arr[sizeof(a)];
memcpy(arr,&a,sizeof(a));
like image 167
vmatyi Avatar answered Sep 18 '22 13:09

vmatyi


To make a character string representing the number in human-readable form, use snprintf(), like in code below.

To access the bytes of the double, use a union. For example, union u { double d; char arr[8]; }

However, from your added comment, perhaps you mean to convert a number from characters to double. See the atof() call in code below. The code produces the following 4 output lines:

u.d = 2.132000     u.arr =  75 ffffff93 18 04 56 0e 01 40
res = 2.13200000
u.d = 37.456700     u.arr =  ffffffa6 0a 46 25 75 ffffffba 42 40
res = 37.45670000

Code:

#include <stdio.h>
#include <stdlib.h>
union MyUnion { char arr[8];  double d; };

void printUnion (union MyUnion u) {
  int i;
  enum { LEN=40 };
  char res[LEN];
  printf ("u.d = %f     u.arr = ", u.d);
  for (i=0; i<8; ++i)
    printf (" %02x", u.arr[i]);
  printf ("\n");
  snprintf (res, LEN, "%4.8f", u.d);
  printf ("res = %s\n", res);
}
int main(void) {
  union MyUnion mu = { .d=2.132 };
  printUnion (mu);
  mu.d = atof ("37.4567");
  printUnion (mu);
  return 0;
}
like image 26
James Waldby - jwpat7 Avatar answered Sep 18 '22 13:09

James Waldby - jwpat7