thundium
thundium

Reputation: 1063

Convert one 32bit float number into two 16bit uint number and then convert back to that 32bit float again

I am working on transfter an 32bit float number from one platform to the other. Well it is only allowed to pass 16bit unsinged int member to the transfter register. I am thinking that I can then seperate the 32bit float into two 16bit and then conver to 32bit on the other side again.

(I am using C language)

Like:

float A = 3.14
uint16_t B = A & 0xffff;
uint16_t C = A & 0xffff0000;

float D = C<<16 & B;

Obevious this is not correct as float data will be converted to unsigned int when it is assigned. So how shall I do it usually? there shall be some quite mature methods to do similiar thing

Thanks

Upvotes: 1

Views: 1095

Answers (1)

Paul R
Paul R

Reputation: 212979

You can use a union for this, e.g.:

typedef union {
    float f;
    uint16_t a[2];
} U;

U u;

u.f = 3.14f;

printf("%g -> %#x %#x\n", u.f, u.a[0], u.a[1]);

LIVE DEMO

Note: strictly speaking this is undefined behaviour, but it's such a widely used technique that it is unlikely to fail. Alternatively you can take a safer, but potentially somewhat less efficient approach, and just use memcpy, like this:

float f = 3.14f;
uint16_t a[2];
memcpy(a, &f, sizeof(a));
printf("%g -> %#x %#x\n", f, a[0], a[1]);

LIVE DEMO

Upvotes: 5

Related Questions