簡體   English   中英

打印數字的二進制表示

[英]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);

產量

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM