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

What is the difference between : int a = (b<<2) >>2; and int a = b & 0x3F; when b is an unsigned char?

i find a strange case:
when b=0x40 which is 64,

int a = b & 0x3F
output is 0

int a = (b<<2) >> 2
output is 64.
WHY IT IS 64?

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

1000 0000 << 2 = 0000 0000 and it should be 0?

I asked gpt and it runs them on the python, which turns out 64 again. I dont know why.

>Solution :

All integer arithmetic in C is done in the int type or wider. Any operand narrower than an int is automatically either promoted to int or converted to an even wider type to match another operand.

In b<<2, the unsigned char b is automatically promoted to int before the shift. Then shifting 64 left two bits produces 256, an int value. Shifting it right two bits produces 64, and that is used to initialize a.

If you want an unsigned char value from the left shift, use a cast to convert the int result to unsigned char:

int a = (unsigned char) (b << 2) >> 2;
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