Answer the question
In order to leave comments, you need to log in
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;
}
33
-31
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question