打印数字的二进制表示

printing the binary representation of a number

下面打印数字二进制表示的代码有什么问题?

int a = 65;
for (int i = 0; i < 8; i++) {
    cout << ((a >> i) & 1);
}

您从数字中的最低有效位开始并首先打印它。但是,无论您首先打印什么,都是典型二进制表示中的最高有效数字。

65 是 01000001 所以这就是你的循环迭代的方式

01000001
       ^   Output: 1

01000001
      ^    Output: 10

01000001
     ^     Output: 100

...

01000001
^          Output: 10000010

因此打印输出是相反的。最简单的修复方法是更改​​循环的顺序。

for (int i = 7; i >= 0; i--) {
   cout << ((a >> i) & 1);
}

C 中的 int 通常是 32 位。所以这对我有用

void binary(unsigned n) {
    unsigned i;
    // Reverse loop
    for (i = 1 << 31; i > 0; i >>= 1)
        printf("%u", !!(n & i));
}

. . .

binary(65);

Output

00000000000000000000000001000001

除了仅生成二进制字符串之外,有时为了比较或可读性目的,能够指定结果字符串的长度也是有益的。下面的小函数将获取一个数字和长度(整数二进制字段的位数)并将其作为字符提供以供使用或打印。稍加努力,您还可以将字符串分解为格式化的部分。 (例如 16 位数字:0034-4843-2392-6720

尝试以下操作:

#include <stdio.h>
#include <stdlib.h>

/* BUILD_64 */
#if defined(__LP64__) || defined(_LP64)
# define BUILD_64   1
#endif

/* BITS_PER_LONG */
#ifdef BUILD_64
# define BITS_PER_LONG 64
#else
# define BITS_PER_LONG 32
#endif

char *binpad (unsigned long n, size_t sz);

int main (int argc, char **argv) {

    int n = argc > 1 ? atoi (argv[1]) : 251;
    size_t sz = argc > 2 ? (size_t) atoi (argv[2]) : 8;

    printf ("\n %8d  :  %s\n\n", n, binpad (n, sz));

    return 0;
}

/** returns pointer to binary representation of 'n' zero padded to 'sz'.
*  returns pointer to string contianing binary representation of
*  unsigned 64-bit (or less ) value zero padded to 'sz' digits.
*/
char *binpad (unsigned long n, size_t sz)
{
    static char s[BITS_PER_LONG + 1] = {0};
    char *p = s + BITS_PER_LONG;
    register size_t i;

    for (i = 0; i < sz; i++)
        *--p = (n>>i & 1) ? '1' : '0';

    return p;
}

输出

$ binprnex

  251  :  11111011

$ binprnex 42869 16

42869  :  1010011101110101