0

Objective is to print binary output of -ve or +ve integers and output is correct when we declare variable with signed, but not able to understand the behaviour when variable is declared as unsigned.

  int main() {
      unsigned char num = -1; /* unsigned int */
      int i = 0;
      /* Loop to print binary values */
      for (i = 0 ; i < 8; i++) {
        if(num & 128u)
        {
         printf("1 ");
        }
        else 
        {
         printf("0 ");
        }
        num= num<<1;
      }
      printf("\n");
      return 0;
    }

output is printed as "1 1 1 1 1 1 1 1"

which is equal to -1; But i have given unsigned int as input. How this works?

Mohan
  • 1,871
  • 21
  • 34
Monty
  • 27
  • 3

1 Answers1

0

When you doing

unsigned char num = -1; /* unsigned int */

It storing in num is 255 (Max Number) in decimal. So in every loop if(num & 128u) is satisfying so the o/p is ....

/* output is printed as "1 1 1 1 1 1 1 1" */

There are some more mistakes in question you are saying abot int but in program you have taken char variable and storing signed number in unsigned variable so , you will not get o/p what you expect.

Mohan
  • 1,871
  • 21
  • 34
  • Thanks , this give some idea.. but given a binary representation of numbers can we know it is signed or unsigned int. I want to convert binary to decimal .. – Monty Dec 14 '15 at 10:30
  • signed binary representation may help you .....http://stackoverflow.com/questions/3952123/representation-of-negative-numbers-in-c – Mohan Dec 14 '15 at 11:31
  • how to know if a binary number represents a negative number? ....http://stackoverflow.com/questions/7794653/how-to-know-if-a-binary-number-represents-a-negative-number – Mohan Dec 14 '15 at 11:38