浮动到固定转换 [英] Float to fixed conversion

查看:190
本文介绍了浮动到固定转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个基本问题,但我很困惑。

This is a basic question but I am confused.

我有一个格式为1.4.12的寄存器。这意味着它需要一个浮点,并采取范围-15.9999 - 15.9999,是正确的,或多少九?我对范围感到困惑。

I have a register which has the format 1.4.12. Meaning it takes a float and takes the range -15.9999 - 15.9999, is that correct, or how many nines? I am confused by the range.

我需要将c ++ float转换为固定点并将其放入寄存器中?有没有任何std ::库来做C?

I need to convert a c++ float to fixed point and put it in the register? Are there any std:: libraries to do that in C? If not is there any standard code that someone could point me to?

另外,如何将fixed转换为float将是好的?

Also, how to convert fixed to float would be good?

推荐答案

这是很容易做到这一点:

It's fairly simple to do this yourself:

typedef int32_t fixed;

fixed float_to_fixed(float x)
{
    return (fixed)(x * 65536.0f / 16.0f);
}

注意,这没有范围检查,所以如果 x 可能在您的固定点类型的有效范围之外,那么您可能希望添加一些检查,并适当饱和或抛出错误。

Note that this has no range checking so if x can possibly be outside the valid range for your fixed point type then you might want to add some checks and either saturate or throw an error as appropriate.

类似地,在另一个方向上转换:

Similarly for conversion in the other direction:

float fixed_to_float(fixed x)
{
    return (float)x * 16.0f / 65536.0f;
}

(这个当然不需要任何范围检查。)

(This one does not need any range checking of course.)

这篇关于浮动到固定转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆