printing the binary representation of a number

陌路散爱 提交于 2019-12-10 06:39:29

问题


What is wrong with the below code which prints the binary representation of a number?

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

回答1:


You're starting at the least significant bit in the number and printing it first. However, whatever you print first is the most significant digit in the typical binary representation.

65 is 01000001 so this is how your loop iterates

01000001
       ^   Output: 1

01000001
      ^    Output: 10

01000001
     ^     Output: 100

...

01000001
^          Output: 10000010

Thus the printed output is in reverse. The simplest fix is to change the order of the loop.

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



回答2:


An int in C is typically 32 bits. So this works for me

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

. . .

binary(65);

Output

00000000000000000000000001000001



回答3:


In addition to just producing a binary string, sometimes it is beneficial to be able to specify the length of the resulting string for comparison or readability purposes. The following little function will take a number and length (number of digits int binary field) and provide that as a character for use or printing. With slightly more effort you can also break the sting up into formatted sections. (e.g. 16 digits: 0034-4843-2392-6720)

Try the following:

#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;
}

Output

$ binprnex

  251  :  11111011

$ binprnex 42869 16

42869  :  1010011101110101


来源:https://stackoverflow.com/questions/32488011/printing-the-binary-representation-of-a-number

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!