0

Why this snap of code prints -64? I'm not sure that I understand the shifting right, but it seems odd.

char t = 0x80; 
printf("%i", t); //print -128 => 0b10000000
printf("%i", t>>1); //print -64 => 0b11000000, not 0b01000000
wirkl
  • 11
  • 1
  • The sign bit remains extended through the shift operation on your implementation. Do not attempt to shift in-to, nor out-of, the sign bit of a signed value in C. – WhozCraig Aug 03 '20 at 20:13
  • the value printed is most certainly not 0b11000000!! the printed value is of type int and it is at least 16 bits wide i.e. 0b1111111111000000 and more likely 32-bit 0b11111111111111111111111111000000 – Antti Haapala -- Слава Україні Aug 03 '20 at 20:17
  • Look at this: https://learn.microsoft.com/en-us/cpp/cpp/left-shift-and-right-shift-operators-input-and-output?view=vs-2019#code-try-4 – Andy Aug 03 '20 at 20:17
  • `char t = 0x80;` itself is weak code. When `char` is _signed_, such an assignment leads to _implementation defined behavior_. Better to use `t = -128;` – chux - Reinstate Monica Aug 03 '20 at 23:05
  • What if I use char as byte? And I want to write some 0xNN directly? I know, that 0x80 is not the best way, but anyway. – wirkl Aug 04 '20 at 20:17

0 Answers0