user3681077
user3681077

Reputation: 25

retrieving bits from bytes

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.

Upvotes: 1

Views: 94

Answers (3)

Sani Huttunen
Sani Huttunen

Reputation: 24395

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

Upvotes: 0

MOHAMED
MOHAMED

Reputation: 43616

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

Upvotes: 0

unwind
unwind

Reputation: 400129

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.

Upvotes: 1

Related Questions