in Programming and DS recategorized by
3,057 views
3 votes
3 votes

What is the output of the following $\text{’C’}$ program?

main()
{
    printf(“%x”,-1>>4);
}
  1. $\text{ffff}$
  2. $\text{0fff}$
  3. $\text{0000}$
  4. $\text{fff0}$
in Programming and DS recategorized by
3.1k views

4 Answers

8 votes
8 votes

Answer : D

They are asking to print ("%x",-1>>4); this

Lets take this A/C to Answer given write the 1 in 16 bits

0000 0000 0000 0001

-1 can be written in 2's complement no system as

1111 1111 1111 1111

">>" This Operator is called Binary Right Shift Operator ,So we have to right shift the o/p bits and fill the shifted bits with 0

0000 1111 1111 1111

   0       F      F       F

edited by

4 Comments

nopes >> is right shift operator      left shift is <<
0
0
but the link says it is left shift you click on it
0
0
order in heading is wrong in the click read it further
0
0
5 votes
5 votes

-1 (2'scomplement)

0000 0000 0000 0001 (1)

1111 1111 1111 1111(2's complement) -----   -1

>>4 right shifts 4 bits

0000 1111 1111 1111  

=0FFF which is option B

Option B

1 comment

Nice explanation
0
0
4 votes
4 votes

According to The C Programming language by Dennis M. Ritchie , Page 49 Second Paragraph

Right Shifting a signed quantity will fill with sign bits on some machines and with "0-bits" on others.

Suppose int occupies 2 Bytes then -1 will be represented as 11111111 11111111 in 2's complement form

Right Shifting it by 4 bits and fill with sign bits 11111111 11111111 = ffff  // %x  prints answer in hexadecimal form

Right Shifting it by 4 bits and fill with 0 bits 00001111 11111111 = offf

Both A and B are correct. It depends on machines.

2 votes
2 votes
a>>b if b is negative then result is unpredictable

        if a is negative then result depends on whether sign extension is performed or not by the machine on which a program is executed.

-1 will be stored in memory as its 2's complement as 1111 1111 1111 1111

on machine on which sign extension is performed -1>>4 will output 1111 1111 1111 1111 i.e. ffff

on machine on which sign extension is not performed -1>>4 will output 0000 1111 1111 1111 i.e. 0fff

On most of the compiler like turbo c,Codeblocks etc sign extension is done so (a) will be the answer.

3 Comments

You mean vacant bit will be '1,s' while doing right shift with negative number rt?

This program will give same output for (-1 to -16). rt?

0
0
@ManojK sir,

shouldn't the answer be compiler dependent...?
0
0
@ManojK sir

Yes same output if sign extension is performed by compiler else if sign extension is not performed then different output according to integer on which shift is performed

@Kapilp sir,

Yes it will be compiler dependent whether sign extension is allowed or not
0
0

Related questions