Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print binary representation of a number

I want to print the binary representation of an int. My solution seems to work for both int and unsigned int in Visual Studio, but somebody told me it's wrong. Does anyone see an error? If so, why does my program seem to work for me?

void printbin(int n)
{
    unsigned int i = 1<<31;

    for (int j=0; j<32; j++)
    {
        if ((n & i) != 0)
            printf("1");
        else
            printf("0");
        i = i>>1;
    }

    printf("\n");
}
like image 343
thambi03 Avatar asked Apr 21 '15 20:04

thambi03


People also ask

How do you print binary numbers?

To print binary representation of unsigned integer, start from 31th bit, check whether 31th bit is ON or OFF, if it is ON print “1” else print “0”. Now check whether 30th bit is ON or OFF, if it is ON print “1” else print “0”, do this for all bits from 31 to 0, finally we will get binary representation of number.

How do you print a binary representation of a number in Python?

Use a formatted string literal to print the binary representation of a number, e.g. print(f'{number:b}') . Formatted string literals enable us to use the format specification mini-language which can be used to get the binary representation of a number.

How do you write a number represented in binary?

To convert integer to binary, start with the integer in question and divide it by 2 keeping notice of the quotient and the remainder. Continue dividing the quotient by 2 until you get a quotient of zero. Then just write out the remainders in the reverse order.

How do you represent a binary number in C++?

Step 1: Initialize the number variable with zero. Step 2: Store the remainder by computing bin%10; we perform this step to get the equivalent decimal number for the binary number. Step 3: Use the division operator and divide the binary number by 10; this step helps compute the next least significant bit.


1 Answers

1<<31 shifts a bit passed the value bits and potentially into a sign (or padding) bit. This is undefined behavior in C.

n & i is attempting to "and" bits of an unsigned int and the sign of a signed int.

OP's use of 32 assumes an int is 32-bits wide.

Following is an example the prints the sign and the variable number of bits - works [INT_MIN...INT_MAX].

#include <limits.h>
void printbin_c(int n) {
  char buf[CHAR_BIT * sizeof n + 1];
  char *p = &buf[sizeof buf - 1];
  *p = '\0';

  int i = n;
  if (i > 0) {
    i = -i;
  }

  do {
    p--;
    *p = '0' - i%2;
    i /= 2;
  } while (i);

  if (n < 0) {
    p--;
    *p = '-';
  }

  puts(p);
}

[Edit] Cope with 1's complement @John Bollinger

Using the negative absolute value with if (i > 0) i = -i; as the positive absolute value does not work well with INT_MIN 2's complement.

like image 107
chux - Reinstate Monica Avatar answered Oct 25 '22 15:10

chux - Reinstate Monica