【发布时间】:2016-01-28 03:46:00
【问题描述】:
我正在尝试使用unsigned 整数来表示一个数字(浮点表示)的bit16 表示。这里的小数域偏离标准的10,为8位——暗示指数域为7位,符号为1位。
我的代码如下:
bit16 float_16(bit16 sign, bit16 exp, bit16 frac) {
//make the sign the number before binary point, make the fraction binary.
//concatenate the sign then exponent then fraction
//
bit16 result;
int theExponent;
theExponent = exp + 63; // bias = 2^(7-1) + 1 = 2^6 + 1 = 63
//printf("%d",sign);
int c, k;
for(c = 6; c > 0; c--)
{
k = theExponent >> c;
if( k & 1)
printf("1");
else
printf("0");
}
for(c = 7; c >= 0; c--)
{
k = frac >> c;
if( k & 1)
printf("1");
else
printf("0");
}
//return result;
}
我从这些字段“重新创建”16 bit 序列的想法是将它们连接在一起,但如果我想在进一步的应用程序中使用它们,我无法这样做。有没有办法在所有内容都被打印(16-bit 序列)之后将最终结果存储到一个变量中,然后可以将其表示为一个无符号整数?还是有更优化的方法来执行此过程?
【问题讨论】:
-
不能存储 printf 的结果。您可以使用
sprintf,但在这种情况下,仅在 char 数组中设置单个字符可能更简单。 -
@M.M,这是一个 typedef unsigned int。
-
为什么不直接使用 C 标准
uint16_t? -
@owacoder 我的任务要求我以其他方式实现它。
标签: c floating-point bit 16-bit