memcpy is a built-in function requiring the header "string.h". Depending on your application scenario, if you want to avoid the use of memcpy plus your char array is 4-byte aligned, here is my preferred way based on static casting in gcc-like compilers.
Copy amount (float) to array (char*)
float amount = 0.01;
char array[4] __attribute__((aligned(4)));
*((float *)array) = amount;
Copy bytes (char*) to f (float)
float f;
char bytes[4] __attribute__((aligned(4)));
f = *((float *) bytes);
Alternatively, here is one more way that I believe will work under any compilers, regardless of byte alignment:
First, define a dummy struct with four bytes (a float takes four bytes. or alternatively, use sizeof(float) in place of 4).
typedef struct {char fourBytes[4]; } FourBytes ;
Use it as follows:
float amount = 0.01;
char array[4] ;
// copy from amount to array
*((FourBytes *)array) = *((FourBytes *) (&amount));
// copy from array to amount
*((FourBytes *) (&amount)) = *((FourBytes *)array) ;
From a functional perspective, a third alternative may be just to use a union structure:
union DATA
{
float f;
char array[4];
}; // array is forced to 4-byte aligned
Use it as follows:
union DATA data1;
union DATA data2;
// copy data between the two
data1.f = data2.f
floator do you mean reverse the order of the bytes, making the last byte first, the first last, and so on?printf("%g\n", f);appended to it (and also wrapped in#include <stdio.h> /#include <string.h>` /int main(void) { … }). It prints “0.01”.