I have a question about float 4byte data.

Asked 2 years ago, Updated 2 years ago, 83 views

iobyte[0][0] = 44 , iobyte[0][1] = e8 , iobyte[0][2] = 35 , iobyte[0][3] = 42

There is data that came in in the same form as

Let's say 44e83542 in which the value of the float's real stored form is sequentially listed.

How should I save it in float to read the normal float value?

c type float casting variable

2022-09-22 12:59

1 Answers

I think you can convert it and read it.

#include <stdio.h>
#include <string.h>
typedef unsigned char uchar;

float bytesToFloat(uchar b0, uchar b1, uchar b2, uchar b3)
{
    float output;

    *((uchar*)(&output) + 3) = b0;
    *((uchar*)(&output) + 2) = b1;
    *((uchar*)(&output) + 1) = b2;
    *((uchar*)(&output) + 0) = b3;

    return output;
}

int main(){
    float f = 2.45f;
    char a[sizeof(float)];
    memcpy(a, &f, sizeof(float));
    printf("%f\n", bytesToFloat(a[3],a[2], a[1], a[0]));
    return 0;
}

The parameter input order can be entered in order after checking if it is Big Endian or Little Endian.


2022-09-22 12:59

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.