C Programming - Bitwise Operators - Discussion

Discussion Forum : Bitwise Operators - Find Output of Program (Q.No. 3)
Assuming a integer 2-bytes, What will be the output of the program?

int main()
    printf("%x\n", -1<<3);
    return 0;
Answer: Option

The system will treat negative numbers in 2's complement method.


Assume the size of int is 2-bytes(16 bits). The integer value 1 is represented as given below:

Binary of 1: 00000000 00000001 (this is for positive value of 1)

1's complement of binary 1: 11111111 11111110
2's complement of binary 1: 11111111 11111111

Thy system will store '11111111 11111111' in memory to represent '-1'.

If we do left shift (3 bits) on 11111111 11111111 it will become as given below:

11111111 11111111 ---(left shift 3 times)---> 11111111 11111000.

So, 11111111 11111000 ---(binary to hex)---> FF F8. (Required Answer)


How is the negative number obtained from 2's complement value?

As stated above, -1 is represented as '11111111 11111111' in memory.

So, the system will take 2's complement of '11111111 11111111' to the get the original negative value back.


Bit Representation of -1: 11111111 11111111

Since the left most bit is 1, it is a negative number. Then the value is

1's complement: 00000000 00000000
2's complement: 00000000 00000001 (Add 1 to the above result)

Therefore, '00000000 00000001' = 1 and the sign is negative.

Hence the value is -1.

5 comments Page 1 of 1.

Dedeepya said:   7 years ago
Here in the program bit wise operator "<<" indicates left shift operator.

Manjula said:   8 years ago
Here, why we have to take left shift?

Vamsi said:   9 years ago
I didn't understand any about the -1 in the given answer.

Madhuri Agrawal said:   9 years ago
As 32 will be written as 100000 in its binary format preceded by all 0's.

So when we do negation of the same, so it will give the output as: 011111 preceded by any number of 1's.

Now coming to converting the same bit string in its hexadecimal format. So it will result in 'df' preceded by as many number of 'f' as we want.

Sanju said:   1 decade ago
You have given:

Fill with 1s in the left side for right shift for negative numbers.

Then why this?

Post your comments here:

Your comments will be displayed after verification.