简体   繁体   English

将一个32位浮点数转换为两个16位uint数,然后再次转换回该32位浮点数

[英]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. 我正在从一个平台向另一个平台转移32位浮点数。 Well it is only allowed to pass 16bit unsinged int member to the transfter register. 好吧,它只允许将16位未ing的int成员传递给transfter寄存器。 I am thinking that I can then seperate the 32bit float into two 16bit and then conver to 32bit on the other side again. 我在想,然后可以将32bit浮点数分成两个16bit,然后在另一侧再次转换为32bit。

(I am using C language) (我正在使用C语言)

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. 显然这是不正确的,因为在分配浮点数据时会将其转换为unsigned int。 So how shall I do it usually? 那么我通常应该怎么做? there shall be some quite mature methods to do similiar thing 会有一些相当成熟的方法来做类似的事情

Thanks 谢谢

You can use a union for this, eg: 您可以为此使用联合,例如:

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: 另外,您可以采用一种更安全,但可能效率较低的方法,并使用memcpy,如下所示:

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 现场演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM