-1

I am studying for an interview and found this question a bit bewildering. Would appreciate your advise.

What happens to the left side of an unsigned number after performing a bit-shift operation to the right?

1. the number will be filled with 1's on the left

2. the method of the numbers being filled on the left depends on the system

3. all answers are wrong

4. the number will be filled with 0's on the left

5. the left part of the number will be filled with the bits that were lost from the right
Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
jrz
  • 1,213
  • 4
  • 20
  • 54

1 Answers1

3

The answer is (4).

If it had been a signed int, then most compilers would fill the left bits with 1's if the sign bit is 1 (i.e. if the number is negative), or with 0's if the sign bit is 0. But this is implementation-defined.

(5) is there to trip you up if you happen to know some assembly. It would be correct if it were a rotate operation, which is not supported by the C language.

Howlium
  • 1,218
  • 1
  • 8
  • 19
  • 2
    Re “If it had been a signed int, then the left bits would be filled with 1's if the sign bit is 1”: C 2018 6.5.7 5 says “If `E1` [the left operand of `>>`] has a signed type and a negative value, the resulting value is implementation-defined.” – Eric Postpischil Aug 02 '20 at 11:16
  • Thanks; I've modified my answer to reflect that. – Howlium Aug 10 '20 at 21:31
  • 1
    Note that “implementation-defined” is stronger than “implementation-dependent.” Any behavior not fully specified by the C standard is implementation-dependent. But “implementation-defined” means the C standard requires that the implementation document what choice it makes. – Eric Postpischil Aug 10 '20 at 22:22