C / C ++ - 转换的24位有符号整数浮动 [英] C/C++ - Convert 24-bit signed integer to float

查看:1353
本文介绍了C / C ++ - 转换的24位有符号整数浮动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用C ++编程。我需要转换为24位有符号整数(存储在一个3字节数组)浮(正火[-1.0,1.0])。

I'm programming in C++. I need to convert a 24-bit signed integer (stored in a 3-byte array) to float (normalizing to [-1.0,1.0]).

在x86平台是MSVC ++(这意味着输入是小端)。

The platform is MSVC++ on x86 (which means the input is little-endian).

我试过这样:

float convert(const unsigned char* src)
{
    int i = src[2];
    i = (i << 8) | src[1];
    i = (i << 8) | src[0];

    const float Q = 2.0 / ((1 << 24) - 1.0);

    return (i + 0.5) * Q;
}

我不能完全肯定,但似乎我从这个code得到的结果是不正确的。所以,是我的code错了,如果是这样,为什么?

I'm not entirely sure, but it seems the results I'm getting from this code are incorrect. So, is my code wrong and if so, why?

推荐答案

您没有符号扩展24位成整数;上部比特永远是零。这code将工作不管你的 INT 尺寸是:

You are not sign extending the 24 bits into an integer; the upper bits will always be zero. This code will work no matter what your int size is:

if (i & 0x800000)
    i |= ~0xffffff;

编辑:第2题是您的比例常数。简单地说,要由旧最大新的最大值和分相乘,假设0转换后保持在0.0

Problem 2 is your scaling constant. In simple terms, you want to multiply by the new maximum and divide by the old maximum, assuming that 0 remains at 0.0 after conversion.

const float Q = 1.0 / 0x7fffff;

最后,为什么你最终转化加入0.5?我能理解,如果你试图舍入到一个整数值,但你要去另一个方向。

Finally, why are you adding 0.5 in the final conversion? I could understand if you were trying to round to an integer value, but you're going the other direction.

编辑2:您指向该人士对你的选择有很详细的理由。不是我会选择,但完全站得住脚仍然方式。我对乘数的建议仍持有,但最大的不同是因为0.5加系数:

Edit 2: The source you point to has a very detailed rationale for your choices. Not the way I would have chosen, but perfectly defensible nonetheless. My advice for the multiplier still holds, but the maximum is different because of the 0.5 added factor:

const float Q = 1.0 / (0x7fffff + 0.5);

由于正和负幅值是在加入后的相同,这应正确缩放​​两个方向

Because the positive and negative magnitudes are the same after the addition, this should scale both directions correctly.

这篇关于C / C ++ - 转换的24位有符号整数浮动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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