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?