我没有找到有关“Q23定点表示”你的机器使用的任何详细信息,所以我做了我自己的定义,写了一些转换例程和测试他们对一些几个值:
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
/**
* q23 is a fixed-point two's-complement type:
* - 1 bit sign,
* - 8 bit integer part,
* - 23 bit fraction part.
*
* long is assumed to be 32 bit two's complement without padding bits.
*/
typedef long q23;
static q23
cvt_float_to_q23(float f) {
return f * (1 << 23);
}
static float
cvt_q23_to_float(q23 x) {
return ((float) x)/(1 << 23);
}
/*
* Here starts the testing code.
*/
static unsigned errors = 0;
static void
assert_q23_is(q23 fixed, float f) {
if (cvt_q23_to_float(fixed) != f) {
fprintf(stderr, "E: cvt_q23_to_float(%08lx) expected %.10f, got %.10f\n",
fixed, f, cvt_q23_to_float(fixed));
errors++;
}
}
static void
assert_float_is(float f, q23 fixed) {
if (cvt_float_to_q23(f) != fixed) {
fprintf(stderr, "E: cvt_float_to_q23(%f) expected %08lx, got %08lx\n",
f, fixed, cvt_float_to_q23(f));
errors++;
}
}
static void
assert_equals(q23 fixed, float f) {
assert_q23_is(fixed, f);
assert_float_is(f, fixed);
}
int
main() {
/* Some values have equivalent representation. */
assert_equals(LONG_MIN, -256.0f);
assert_equals(LONG_MIN/2, -128.0f);
assert_equals(0, 0.0f);
assert_equals(LONG_MAX/2 + 1, 128.0f);
/* There will be a fixpoint ... */
assert_float_is(1.0/3, 0x002aaaaa);
assert_q23_is(0x002aaaaa, 0.3333332539f);
/* float only has 24 bits of precision */
assert_equals(0x2aaaaac0, 256.0/3);
if (errors == 0) {
printf("ok\n");
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
一些言论:
- 如果您需要饱和四舍五入,你必须实现一个自己通过检查参数
cvt_float_to_q23
。
- 到处会出现舍入错误,它们是不可避免的。一定要妥善处理它们。
让我知道是否有人有一些想法。 – Viks 2010-08-20 17:11:45
这是什么'32765'?在十六进制中它是'0xfffd',所以这对我来说完全是意料之外的。你为什么不改用'0x10000'? – 2010-10-16 13:34:19