Floating point 具有不同比例因子的浮点到固定转换
当我将固定转换为浮动和浮动转换为固定时,有人能告诉我这些方法之间的区别吗 (a)Floating point 具有不同比例因子的浮点到固定转换,floating-point,fixed-point,Floating Point,Fixed Point,当我将固定转换为浮动和浮动转换为固定时,有人能告诉我这些方法之间的区别吗 (a) inta=32767; 浮点b=32765*(1/32767)//16位比例因子 int c=b*32767 (b) inta=32767; 浮点b=32765*(1/1.0)//比例因子=1 int c=b*1 (a) inta=32767; 浮点b=32765*(1/0x80000)//24位比例因子 int c=b*(0x80000) 如果我的机器使用Q23定点表示法,我应该使用哪一种?我没有找到关于您的机器
inta=32767;
浮点b=32765*(1/32767)//16位比例因子
int c=b*32767代码>
(b)
inta=32767;
浮点b=32765*(1/1.0)//比例因子=1
int c=b*1代码>
(a)
inta=32767;
浮点b=32765*(1/0x80000)//24位比例因子
int c=b*(0x80000)代码>
如果我的机器使用Q23定点表示法,我应该使用哪一种?我没有找到关于您的机器使用的“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;
}
#包括
#包括
#包括
/**
*q23是一种定点二补类型:
*-1位符号,
*-8位整数部分,
*-23位小数部分。
*
*假定long是32位2的补码,不带填充位。
*/
typedef长q23;
静态q23
cvt浮球至浮球q23(浮球f){
返回f*(1如果有人有什么想法,请告诉我。这是什么32765
?在十六进制中是0xfffd
,所以这对我来说是完全意外的。为什么不改为0x10000
?