Float to fixed conversion

旧城冷巷雨未停 提交于 2019-12-10 11:47:31

问题


This is a basic question but I am confused.

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.

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?

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


回答1:


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);
}

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.)



来源:https://stackoverflow.com/questions/28483652/float-to-fixed-conversion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!