Wojciech Szabowicz
Wojciech Szabowicz

Reputation: 4198

Bit Shifting and masking

I have a question I am not great if it comes to low level programming so quick question I have a byte and each 2 bits in that byte mean something for example:

my byte is 204 so that should be 1100 1100 according to calculator so

bits 0..1 mean status of type 1
bits 3..2 mean status of type 2
bits 5..4 mean status of type 3
bits 7..6 mean status of type 6

So to check all values I use:

var state = 204
var firstState = (state >> 0) & 2
var secondState = (state  >> 2) & 2
var thirdState = (state >> 4) & 2
var fourthState = (state >> 6) & 2

But this looks odd I expext results
firstState = 0 secondState = 3 thirdState = 0 fourthState =3 but I am receiving 0,2,0,2. So what am I doing wrong?

Upvotes: 1

Views: 400

Answers (1)

Sean
Sean

Reputation: 62472

You need to mask with 3 (11 in binary), not 2 (10 in binary):

var state = 204;
var firstState = (state >> 0) & 3;
var secondState = (state  >> 2) & 3;
var thirdState = (state >> 4) & 3;
var fourthState = (state >> 6) & 3;

When masking the operation is applied to the the bit in the corresponding location in each value, so:

And 
11001100  (204) 
00000011  (3)
-------- 
00000000  (0)

Whilst

And 
00110011  (51) 
00000011  (3)
-------- 
00000011  (3)

Upvotes: 4

Related Questions