开发者

Cast int16_t memory to float

I have a function f开发者_开发知识库rom an external source that returns an array of 2 uint16_t elements (which I cast to int).

I have already been able to cast these to one "big" int ((i1 << 16) + i2)

Now I need to be able to cast this to float, keeping the point value as is in memory.

Can anyone suggest a way or point me in the right direction?

Thanks in advance!


I suggest to keep very clear that you are messing around and use a memcpy:

float a;
int b;

memcpy(&a,&b,min(sizeof(a),sizeof(b)));

someone might encounter your code when you're long gone, in which case this will show there's something special happening intentionally.


I'd use a union:

union fltconv {
    float f;
    uint32_t i;
} u;
u.i = ((uint32_t) i1 << 16) | i2;
float f = u.f;

It's more explicit about what you're doing. Bear in mind that this is very nonportable.


Perhaps something like this would work?

uint32_t a = ....; // Contains your big int.
float b = *(float*)&a;

Of course that would require you to know int has the same size as float...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜