Вопрос

Sorry to ask this but I have searched for this small thing and found somthing related on this below link but was unable get any idea

  1. How to store floats in array to be used later?

  2. storing in unsigned char array

How to store a float value suppose 0.00895 to an unsigned char which is later used to store in the memory buffer.

And later I need to read the array back and want to read it back from the memory.

Thanks

Это было полезно?

Решение

You don't need memcpy for this... That would be useful if you were copying a float array into a buffer elsewhere in memory. All you really need is to use a different pointer type to look into the character array.

const size_t BUFSIZE = 4096;
char buffer[BUFSIZE];
float *f_buf = (float*)buffer;

If all you wanted was to stick a single float into the start of the buffer, either of the following two lines is okay:

*f_buf = 0.00895;

f_buf[0] = 0.00895;

All it's really doing is letting you see the buffer as an array of floats.

int i;

/* Put a bunch of floats into the buffer */
for( i = 0; i < 10; i++ ) {
    f_buf[i] = i / 2;
}

/* Display contents of buffer in hex */
for( i = 0; i < 10 * sizeof(float); i++ ) {
    printf( "%02x", (int)buffer[i] );
}
printf( "\n" );

/* Sanity-test the buffer contents */
for( i = 0; i < 10; i++ ) {
    printf( "%d: %f\n", i, f_buf[i] );
}

Другие советы

you can copy the memory of the float into the char buffer.

float a;
char buffer[sizeof(float)];
memcpy(buffer,&a,sizeof(float));
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top