Ashwani R
Ashwani R

Reputation: 47

Why does my program print fffffff0?

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?

Upvotes: 0

Views: 4121

Answers (5)

Matteo Italia
Matteo Italia

Reputation: 126927

The << operator is the left shift operator; the result of a<<b is a shifted to the left of b bits.

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, %x is 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 -1 is represented as "all ones"; so, on a computer with 32-bit int you'll have:

11111111111111111111111111111111 = -1 (if interpreted as a signed integer)

now, if you shift this to the left of 4 positions, you get:

11111111111111111111111111110000

The %x specifier makes printf interprets this stuff as an unsigned integer, which, in hexadecimal notation, is 0xfffffff0. This is easy to understand, since 4 binary digits equal a single hexadecimal digit; the 1111 groups in binary become f in hex, the last 0000 in binary is that last 0 in 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.

Upvotes: 6

Phonon
Phonon

Reputation: 12737

It means take bit representation of -1 and shift it to the left 4 times

This means take

11111111 11111111 11111111 11111111 = ffffffff

And shift:

11111111 11111111 11111111 11110000 = fffffff0

The "%x" format specifier means print it out in hexadecimal notation.

Upvotes: 1

Zhuo
Zhuo

Reputation: 86

"<<" is left shift operator. -1<<4 means left shifting -1 by 4. Since -1 is 0xffffffff, you will get 0xfffffff0

More can be found in wiki http://en.wikipedia.org/wiki/Bitwise_operation

Upvotes: 0

Neozaru
Neozaru

Reputation: 1130

"%x" means your integer will be displayed in hexadecimal value.

-1 << 4 means that the binary value of "-1" will be shifted of 4 bits

Upvotes: 0

Mike
Mike

Reputation: 49473

It's the left shift binary operator. You're left shifting -1 by 4 bits:

  -1    == 1111 1111 1111 1111 1111 1111 1111 1111(2) == FFFFFFFF
-1 << 4 == 1111 1111 1111 1111 1111 1111 1111 0000(2) == FFFFFFF0

Upvotes: 0

Related Questions