Printing a binary representation of a number

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

int a = 65;
for (int i = 0; i < 8; i++) {
    cout << ((a >> i) & 1);
}
+4
source share
3 answers

You start with the least significant bit in the number and print first. However, no matter what you print first, this is the most significant digit in a typical binary representation.

65 is this 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 order. The simplest solution is to change the order of the cycle.

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

int in C is usually 32 bits. So it 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);

Exit

00000000000000000000000001000001
0
source

In addition to simply creating a binary string, it is sometimes useful to specify the length of the resulting string for comparison or reading purposes. The next small function will take a number and a length (the number of digits in a binary field) and provide this as a character to use or print. With a little more effort, you can also split the sting 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;
}

Exit

$ binprnex

  251  :  11111011

$ binprnex 42869 16

42869  :  1010011101110101
0
source

Source: https://habr.com/ru/post/1606648/


All Articles