1

Hey so I was wondering if someone could explain how this works, I have to retrieve the 3rd bit from a byte, it is a bool value, and I i'm confused about how this actually works, and also if I have the syntax correct. I keep coming on so many different examples of how to do this. This is what I have:

 if(apdu_parse[0] & (1<<3)){ apdu_bit3 = 1; } else if(apdu_parse[0] & (0<<3)){ apdu_bit3 = 0; } mpdu -> segmented_message = apdu_bit3; 

what i think this does is look for the third bit of apdu_parse[0] determines if its a 1 or a 0 and stores it accordingly. as I said i keep coming across so many different examples that I think i'm starting to blend them and nothings working. the value in apdu_parse[0] is a hex value, I keep getting '93' which makes no sense.

4
  • please show us how apdu_parse, apdu_bit3 and mpdu->segmented_message are defined (what are their types) and how exactly do you print the result? Commented Jun 5, 2014 at 13:27
  • What's this supposed to mean (0<<3) O_ó ? Commented Jun 5, 2014 at 13:27
  • @Pavel: Not necessary to answer his/her question. Commented Jun 5, 2014 at 13:34
  • why not just apdu_bit3 = (apdu_parse[0] >> 3) & 1; Commented Jun 5, 2014 at 13:37

3 Answers 3

1

The first part is right, but the second part is wrong.

This:

if(apdu_parse[0] & (1<<3)){ apdu_bit3 = 1; } 

means "if apdu_parse[0] bitwise-AND:ed with 8 isn't zero", which is fine. It will be true (theifwill be taken) ifapdu_parse[0]` has its 3rd bit set.

The other half though doesn't make any sense; nothing bitwise-ANDed with 0 is non-zero.

I would write it as:

mpdu->segmented_message = (apdu_parse[0] & (1 << 3)) != 0; 

Here an explicit comparison with 0 is made, to create a true/false value, which I think is much cleaner than being implicit about it.

Sign up to request clarification or add additional context in comments.

Comments

0
mpdu->segmented_message = (apdu_parse[0] & (1<<3)) >> 3 

Comments

0

You can simply write:

mpdu->segmented_message = (apdu_parse[0] >> 3) & 1; 

Your code will set the correct value if the bit is set but the wrong value if the bit is not set.

apdu_parse[0] & (0<<3) 

will always generate 0.

Thus

if (adpu_parse[0] & (0<<3)) 

will always be false since

Value AND 0 EQUALS 0 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.