Discussion
Assunming, integer is 2 byte, What will be the output of the program?
#include <stdio.h>
int main()
{
printf("%x\n", -1>>1);
return 0;
}
Answer: A
Correct answer: ffff
\( -1 \) in two's complement is all ones, so on a 2-byte int it is 0xffff.
Right-shifting a signed negative value is implementation-defined, and every common compiler performs an arithmetic shift, propagating the sign bit into the vacated position. All ones shifted right with ones coming in is still all ones, so the result is unchanged at 0xffff, which %x prints as ffff.
Had the shift been logical, a zero would have entered at the top and the answer would have been 7fff. That difference is exactly why shifting negative values is best avoided in portable code.
Post your comment
Please log in or register to post a comment.
Examination Categories
- SSC Exams
- Banking Exams
- Teaching Exams
- Civil Services Exams
- Railways Exams
- Engineering Recruitment Exams
- Defence Exams
- State Government Exams
- Police Exams
- Insurance Exams
- Nursing Exams
- Other Government Exams
- NRA CET
- PG Entrance Exams
- Campus Placement
- MBA Entrance Exams
- CUET and UG Entrance
- Judiciary Exams
- Regulatory Body Exams
- Software Development