Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can unions be used to convert char arrays to float? [duplicate]

I was wondering whether or not is possible to use unions to get a float from a received char array. Let's say that I have defined the following struct

typedef union {
  float f;
  char c[4];
} my_unionFloat_t;

If I receive a char array encoding a float like this ( the numbers are made up)

data[4] = {32,45,56,88};

Can I do the following?

my_unionFloat_t c2f;

c2f.c[0] = data[0];
c2f.c[1] = data[1];
c2f.c[2] = data[2];
c2f.c[3] = data[3];

float result = c2f.f;
like image 353
ndarkness Avatar asked Dec 06 '25 09:12

ndarkness


1 Answers

The easiest way to achieve that in C++ is to use reinterpret_cast:

unsigned char data[4] = {32,45,56,88};
float f = reinterpret_cast<const float&>(data);
const unsigned char* ch =  reinterpret_cast<const unsigned char*>(&f);
for(int i=0; i<4; ++i)
    std::cout << +ch[i] << ' ';
std::cout << f << '\n';
like image 108
chtz Avatar answered Dec 09 '25 20:12

chtz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!