0

I know a left shift operation is being performed on -1 by 1 bit. What I'm not sure about is the binary representation of -1.

Any help would be of great use.

  • The representation depends on the system and the compiler. But in general, see: [two's complement](https://en.wikipedia.org/wiki/Two%27s_complement). – Marco Bonelli Oct 11 '20 at 13:37
  • 1
    Undefined behaviour: see [C11 6.5.7p4](http://port70.net/~nsz/c/c11/n1570.html#6.5.7): "otherwise [`E1` < 0], the behavior is undefined." – pmg Oct 11 '20 at 13:38
  • `-1` is a value of type `int`. Supposing two's complement representation, its binary representation is all-1s, the width of an `int`. But the effect of left-shifting that by any non-zero number of bits is undefined. – John Bollinger Oct 11 '20 at 13:39
  • For an `int`, the binary representation of `-1` is 0xFFFFFFFF. Doing `-1 << 1` produces 0xFFFFFFFE [or -2] – Craig Estey Oct 11 '20 at 13:39
  • What is the output if you try and why does it not answer your question? – Yunnosch Oct 11 '20 at 13:39
  • 2
    @CraigEstey doing `-1 << 1` produces *dragons spitting fire from your computer case*. – Marco Bonelli Oct 11 '20 at 13:39
  • @MarcoBonelli Um, this is one case where the spec is non-sensical. In most H/W the same left shift instruction is used (e.g. there is _no_ "left shift arithmetic" as there is for "right shift arithmetic"). So, the H/W produces the same result regardless of whether C [or any other language] thinks the value is "signed" – Craig Estey Oct 11 '20 at 14:05
  • @CraigEstey C standard says undefined behavior. Famous compilers could have a "sane" implementation, but you cannot assume that unfortunately. – Marco Bonelli Oct 11 '20 at 14:07
  • @MarcoBonelli The C standard is _wrong_. The H/W arch dictates what happens, not the C spec. The question might be _why_ is it [marked as] undefined behavior? Why is `unsigned int x = -1; x <<= 1;` valid [under the spec] when the bit pattern for `-1` is 0xFFFFFFFF regardless of signedness. – Craig Estey Oct 11 '20 at 14:24
  • 1
    @CraigEstey look, we can stay here and argue for days. The C standard is the standard upon which compilers are built. If the standard says undefined behavior, the compiler can do whatever it wants. Period. Whether that is good/bad, right/wrong, blue/red it's all a matter of opinions. Did I say that I think the standard dictates the best way to handle this scenario? No. In fact I do not believe so. Nonetheless, it is what it is. – Marco Bonelli Oct 11 '20 at 14:38
  • @CraigEstey you can argue hardware says this but it is the compiler that compiles the code. FWIW, GCC **does** specify sane 2s complement left-shift always. – Antti Haapala -- Слава Україні Oct 11 '20 at 16:23

0 Answers0