P
P
Pashka232021-12-24 08:32:37
C++ / C#
Pashka23, 2021-12-24 08:32:37

Why does byte shift give different results?

I'm trying to perform the same shift operations on the same variable:

int main() {
  char index = 33;
  char enc = index << 2 >> 2;
  std::cout << (int)enc << std::endl;

  enc = index << 2;
  enc = enc >> 2;
  std::cout << (int)enc << std::endl;
}

but I get different result:
33
-31


I can not understand why the result is different and where did the value -31 come from?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
res2001, 2021-12-24
@Pashka23

Read the section "Bitwise shift operator" here
until it's clear. The point is that if you shifted a signed number to the left so that the most significant digit became 1, then the result will be a negative number. not zero), so the result of shifting a negative number will also be negative (and positive - positive :). If you shift an unsigned number to the right, then the free bits will always be filled with zeros.
By the way, as far as I remember, according to the standard, the character of char is not defined (maybe both signed and unsigned.) You were unlucky with your example, char turned out to be signed, but it made it possible to understand the shifts a little deeper.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question