Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird usage of "&" for a novice C++ programmer

Tags:

c++

I have some code here, and don't really understand the ">>" and the "&". Can someone clarify?

buttons[0] = indata[byteindex]&1;
buttons[1] = (indata[byteindex]>>1)&1;
rawaxes[7] = (indata[byteindex]>>4)&0xf;
like image 493
jello Avatar asked Nov 27 '22 00:11

jello


1 Answers

These are bitwise operators, meaning they operate on the binary bits that make up a value. See Bitwise operation on Wikipedia for more detail.

& is for AND

If indata[byteindex] is the number 4, then in binary it would look like 00000100. ANDing this number with 1 gives 0, because bit 1 is not set:

00000100 AND 00000001 = 0

If the value is 5 however, then you will get this:

00000101 AND 00000001 = 1

Any bit matched with the mask is allowed through.

>> is for right-shifting

Right-shifting shifts bits along to the right!

00010000 >> 4 = 00000001
like image 197
Simon Steele Avatar answered Dec 13 '22 04:12

Simon Steele