如何获得一个任意十进制数字的位

问题描述 投票:0回答:2

例如,我想从列表中一点一点地读取一个int数:十进制列表:[28,171,3,324,66]

第一:28二进制:100111秒:171二进制:10101011...

我试图执行按位运算,但是我不知道二进制文件的长度(例如100111 = 6)。所以我不能按位操作。有什么方法可以读取任意数字?

c binary bit-manipulation bit-shift bitmask
2个回答
0
投票

这里是一个将数字右移至零并从右向左建立缓冲区的版本:

#include <stdio.h>

const char *
bitprt(unsigned int val)
{
    char *bp;
    char *rtn;
    static char buf[128 + 1];

    bp = &buf[sizeof(buf) - 1];
    *bp-- = 0;

    *bp = '0';
    rtn = bp;

    for (;  val != 0;  val >>= 1, --bp) {
        if (val & 1)
            *bp = '1';
        else
            *bp = '0';
        rtn = bp;
    }

    return rtn;
}

void
dotest(unsigned int val)
{
    const char *buf;

    buf = bitprt(val);
    printf("%20u: '%s'\n",val,buf);
}

int
main(void)
{

    dotest(28);
    dotest(171);
    dotest(3);
    dotest(324);
    dotest(66);

    return 0;
}

这是程序的输出:

                  28: '11100'
                 171: '10101011'
                   3: '11'
                 324: '101000100'
                  66: '1000010'

0
投票

如果您试图从整数值中获取位表示,这是一个示例。您必须手动检查每个位,没有内置的实用程序可以循环访问“位”。

#include <stdio.h>

int main(int argc, char const *argv[])
{
  int numbers[] = { 28, 171, 3, 324, 66 };
  int numberslength = (int) (sizeof(numbers) / sizeof(int));

  // each number
  for (int i = 0; i < numberslength; ++i)
  {
    int number = numbers[i];  // get the number
    int mask = 1;             // start at the beginning
    for (int j = 0; j < sizeof(int) * 8; ++j)
    {
      // if the number has a bitwise and in that bit, 1
      printf("%c", number & mask ? '1': '0');

      // move the mask over to the next bit
      mask <<= 1;
    }

    // separate outputs by newline
    printf("\n");
  }

  return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.