浮动到固定的转换
Float to fixed conversion
本文关键字:转换 更新时间:2023-10-16
这是一个基本问题,但我很困惑。
我有一个格式为1.4.12的寄存器。这意味着它需要一个浮动,取值范围为-15.9999-15.9999,是正确的吗,还是多少个9?我被范围弄糊涂了。
我需要将c++浮点转换为定点并将其放入寄存器中?在C中有没有std::库可以做到这一点?如果没有,有没有任何标准代码可以让我参考?
此外,如何将固定转换为浮动会很好?
自己做这件事很简单:
typedef int32_t fixed;
fixed float_to_fixed(float x)
{
return (fixed)(x * 65536.0f / 16.0f);
}
请注意,这没有范围检查,因此如果x
可能在定点类型的有效范围之外,则可能需要添加一些检查,并根据需要饱和或抛出错误。
类似于在另一个方向上的转换:
float fixed_to_float(fixed x)
{
return (float)x * 16.0f / 65536.0f;
}
(这个当然不需要任何范围检查。)
如果需要使用定点,则必须实现加法和乘法运算。在这种情况下,您需要担心为小数部分分配了多少位,为整数部分分配了几个位。然后你可以做";移位";操作作为您的偏好。
在下面的代码片段中,我为小数部分分配了22位,为整数部分分配了9位,从而实现了定点。(附加位将用于符号)
在乘法中,我首先扩展了每个值的位长度以避免溢出。乘法运算后,左移将使乘法运算的输出保持相同的分数部分。
此外,我为输出添加了饱和,以避免任何溢出(如果发生溢出,则输出将保持最大绝对值,无论符号如何)
#include <stdio.h>
#include <math.h>
#include <stdint.h>
#define fractional_bits 22
#define fixed_type_bits 32
typedef int32_t fixed_type;
typedef int64_t expand_type;
fixed_type float_to_fixed(float inp)
{
return (fixed_type)(inp * (1 << fractional_bits));
}
float fixed_to_float(fixed_type inp)
{
return ((float)inp) / (1 << fractional_bits);
}
fixed_type fixed_mult(fixed_type inp_1, fixed_type inp_2)
{
return (fixed_type)(((expand_type)inp_1 * (expand_type)inp_2) >> fractional_bits);
}
fixed_type fixed_add(fixed_type inp_1, fixed_type inp_2)
{
fixed_type inp_1_sign = inp_1 >> (fixed_type_bits - 1);
fixed_type inp_2_sign = inp_2 >> (fixed_type_bits - 1);
fixed_type add = inp_1 + inp_2;
fixed_type add_sign = add >> (fixed_type_bits - 1);
if (inp_1_sign != inp_2_sign)
{
return add;
}
else if (add_sign == inp_1_sign)
{
return add;
}
else if (add_sign == -1)
{
return ((1 << (fixed_type_bits - 2)) - 1 + (1 << (fixed_type_bits - 2)));
}
else if (add_sign == 1)
{
return (1 << (fixed_type_bits - 1));
}
}
相关文章:
- 防止主数据类型C++的隐式转换
- 模板参数替换失败,并且未完成隐式转换
- 努力将整数转换为链表。不知道我在这里做错了什么
- HEX值到wchar_t字符(UTF-8)的转换
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将 Qvector<uint8_t> 转换为 QString
- 如何在cuSparse中使用cusparseXcoo2csr从coo转换为csc
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 在c++中使用nlohmann从类到json的转换
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 如何使用OpenCV将RBG图像转换为HSV,并将H、S和V值保存为C++中的3个独立图像
- 复制列表初始化的隐式转换的等级是多少
- 正在将指针转换为范围
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 将"打开的CV图像"中的"颜色"转换为整数格式
- 是否可以从int转换为enum类类型
- 了解 GLM- openGL 中的相机转换
- 将无符号char*转换为std::istream*C++