I am trying to understand why my program
#include<stdio.h>
void main()
{
printf("%x",-1<<4);
}
prints fffffff0.
What is this program doing, and what does the << operator do?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The
<<operator is the left shift operator; the result ofa<<bisashifted to the left ofbbits.The problem with your code is that you are left-shifting a negative integer, and this results in undefined behavior (although your compiler may place some guarantees on this operation); also,
%xis used to print in hexadecimal an unsigned integer, and you are feeding to it a signed integer – again undefined behavior.As for why you are seeing what you are seeing: on 2’s complement architectures
-1is represented as “all ones”; so, on a computer with 32-bitintyou’ll have:now, if you shift this to the left of 4 positions, you get:
The
%xspecifier makesprintfinterprets this stuff as an unsigned integer, which, in hexadecimal notation, is0xfffffff0. This is easy to understand, since 4 binary digits equal a single hexadecimal digit; the1111groups in binary becomefin hex, the last0000in binary is that last0in hex.Again, all this behavior hereby explained is just the way your specific compiler works, as far as the C standard is concerned this is all UB. This is very intentional: historically different platforms had different ways to represent negative numbers, and the shift instructions of various processors have different subtleties, so the “defined behavior” we get for shift operators is more or less the “safe subset” common to most “normal” architectures.