c - 在 C 语言中,如何使用 printf() 函数将字符串设为 'store'?

标签 c floating-point bit 16-bit

我正在尝试使用 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/

相关文章:

c - 如何在 32 位和 64 位模式下获得相同的 double 运算行为?

c# - 浮点运算 - Double 类型的模运算符

c++ - bitset 未设置正确的值

java - 新字节的二进制表示

java - Android 客户端无法打开到 C 服务器的套接字

c - 生成动态参数 C

B树能有更多的解吗?

python - 对于浮点 x,x==numpy.linspace(x,y,n)[0] 总是 True 吗?

c - OpenGL - 如何让这个程序适用于大于 1x1 的纹理?

c++ - n 位有符号数,其中 n 不是 2 的幂