1

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?

1
  • 1
    should that be & 3 ? or perhaps more clearly: & 0b11 ? Commented Apr 6, 2020 at 13:21

1 Answer 1

4

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) 
Sign up to request clarification or add additional context in comments.

6 Comments

Ok it works, correct me if I am wrong mas is not length but value if I understand correctly?
@WojciechSzabowicz - sorry, I don't understand your comment
@WojciechSzabowicz Yes, when you mask or more properly do bit wise AND it is doing an AND on each bit so it's the value that matters. It is not using the right side as the number of bits to keep
@WojciechSzabowicz - Ah, yes, it's the value of each bit that matters.
@WojciechSzabowicz 3 is a value not the length of bits to take. 3 in bits is 00000011. When you right-shift your state variable, the bits you are looking for is occupying the least-significant bits (000000xx), and when bitwise and ( & ) is applied, you get either 0, 1, 2 or 3.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.