4

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;
msrd0
  • 7,816
  • 9
  • 47
  • 82
ndarkness
  • 1,011
  • 2
  • 16
  • 36

1 Answers1

1

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';
chtz
  • 17,329
  • 4
  • 26
  • 56