Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Question about Bitwise Shift in Microsoft C++

I am doing the following bitwise shift in Microsoft C++:

uint8_t arr[3] = {255, 255, 255};
uint8_t value = (arr[1] << 4) >> 4;

The result of these operations confused me quite a bit:

value = 255

However, if I do the bitwise shift separately:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

value = (arr[i] << 4);
value = value >> 4;

the answer is different and makes much sense:

value = 15

Can someone explain to me why this happens? I am familiar with the concepts of bitwise shift, or so I believed…

Thanks in advance!

(P.S.: It seems g++ will have the same behavior. I am probably missing some important concepts with bitwise shift. Any help is greatly appreciated!)

>Solution :

Expression (arr[1] << 4) will implicitly promote the value of arr[1] to type unsigned int before applying the shift operation, such that the "intermediate" result will not "loose" any bits (cf, for example, the explanation in implicit conversions).

However, when you write value = (arr[i] << 4);, then this "intermediate" result will be converted back to uint_8, and in this step bits get cut off.

See the difference when you write uint8_t value = ((uint8_t)(arr[1] << 4)) >> 4;

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading