【问题标题】:How to represent a number as a 15 bit wide field?如何将数字表示为 15 位宽的字段?
【发布时间】:2017-03-11 16:41:53
【问题描述】:

我想将数字表示为 15 位宽的字段。 所以,例如:

Number        15 bit wide filed representation of the number
 0            000000000000000 /*15 bits*/

'a'           000000001100001 /*15 bits*/

'b'           000000001100010 /*15 bits*/

 4            000000000000100 /*15 bits*/

如果数字可以用更少量的位表示,0 将在其前面。 我在考虑位字段,但是当我尝试这样做时:

#include <stdio.h>
int main()
{
    typedef struct 
    {
        int a : 15;
    }A;
    A b;
    b.a = 0;
   printf("a is %d \n",a.b); 
   return 0;
}

我得到了这个输出:

0

代替:

000000000000000

但是,我说的不仅仅是打印一个数字(我对 %15 或类似的东西不感兴趣)。在我所做的任何操作中,我都希望在任何可以用较少位表示的数字前面都有 0,而不仅仅是打印。

我怎样才能做到这一点?

【问题讨论】:

  • 有点不清楚。您只想以二进制格式打印一个 15 位数字吗?如果是这样,您将不得不进行一些字符串操作。没有您所要求的库实用程序。
  • 不清楚你的问题是什么。您为位域指定的存储的位数总是那么多。对于输出:阅读您使用的函数的手册页怎么样? printf 的文档不仅可以在每个世纪的某一天午夜在喜马拉雅山的一个秘密修道院中找到。
  • @DeiDei 不,正如我所写,我不想只打印。谢谢。
  • @Tree,你在寻找类似string binary = bitset&lt;15&gt;(num).to_string();的东西吗?
  • 对不起,我的问题并非毫无意义。无论如何,“没有数字”是什么意思? @melpomene

标签: c io bit-manipulation field bit


【解决方案1】:

你必须单独检查每一点,像这样:

#include <stdio.h>

#define WIDTH 15

// print the m-th bit (m from 1..16 or 32) of n
void print_bit(n, m)
{
    printf("%d", n & (1 << (m - 1)));
}

typedef struct
{
    int a : WIDTH;
} A;

int main()
{
    A b;
    b.a = 0;

    int i;
    for(i = 1; i <= WIDTH; ++i)
        print_bit(b.a, i);
    return 0;
}

输出:

Georgioss-MacBook-Pro:~ gsamaras$ gcc -Wall main.c 
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out 
000000000000000

阅读更多How do I print one bit?

【讨论】:

  • 非常感谢@gsamaras
  • @Tree 我已对您的问题投了赞成票,该问题有 4 票赞成,但您不接受我的回答,更不用说赞成了!为什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多