我正在尝试使用 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 位
序列是将它们连接在一起,但如果我想在进一步的应用程序中使用它们,我无法这样做。有没有办法在打印完所有内容(16 位
序列)后将最终结果存储到一个变量中,然后可以将其表示为无符号整数?或者是否有更优化的方法来执行此过程?
最佳答案
虽然 printf
在这种情况下不起作用(您不能“存储”它的结果),但您可以使用 sprintf
。
int sprintf ( char * output_str, const char * format, ... );
sprintf
将格式化数据写入字符串
用 printf
上使用 format 时将打印的相同文本组成一个字符串,但内容不是打印(或显示在控制台上),而是作为 C 字符串存储在output_str
指向的缓冲区。
缓冲区的大小应该足够大以包含整个结果字符串。参见 Buffer Overflow .
终止空字符 (\0
) 将自动附加到 output_str
的末尾。
从output_str
到整型变量
您可以使用atoi
函数来执行此操作。您可以在这样的整数变量中得到答案:
int i = atoi (output_str);
关于c - 在 C 语言中,如何使用 printf() 函数将字符串设为 'store'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35052498/