Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens with bitwise shift for all 8 bits

I have a small query in c, I am using the bitwise left shift on number 69 which is 01000101 in binary

01000101  << 8 

and I get answer as 100010100000000

Shouldn't it be all 8 zeros i.e. 00000000 as we shift all the 8 bits to left and then pad with zeros.

like image 865
TechJ Avatar asked Dec 18 '22 19:12

TechJ


1 Answers

It is because of the literal (default data type) for a number (int) is, in most of nowadays CPU, greater than 8-bit (typically 32-bit) and thus when you apply

69 << 8 //note 69 is int

It is actually applied like this

00000000 00000000 00000000 01000101 << 8

Thus you get the result

00000000 00000000 01000101 00000000

If you use, say, unsigned char specifically, then it won't happen:

unsigned char a = 69 << 8; //resulting in 0

This is because though 69 << 8 itself will still result in

01000101 00000000

But the above value will be casted to 8-bit unsigned char, resulting in:

00000000
like image 195
Ian Avatar answered Jan 04 '23 22:01

Ian