Testing bits of a byte

Coding and general discussion relating to the compiler

Moderators: David Barker, Jerry Messina

Post Reply
Jon Chandler
Registered User
Registered User
Posts: 185
Joined: Mon Mar 10, 2008 8:20 am
Location: Seattle, WA USA
Contact:

Testing bits of a byte

Post by Jon Chandler » Mon Jun 15, 2015 9:51 pm

I'm reading 8 input pins on an I2C port expander. The data is read out as a byte. I'm testing the status of each bit with 8 IF/THEN statements testing VARIABLE.BITS(n).

I should be able to do the same thing with a mask and a logical AND, but it's still 8 IF/THEN statements but this still doesn't seem very efficient.

The 8 inputs are independent and there's separate action to take depending on each pin.

Am I missing some easy way of doing this?

Thanks for any ideas.
Jon

Check out the TAP-28 PIC Application board at http://www.clever4hire.com/throwawaypic/

Jerry Messina
Swordfish Developer
Posts: 1473
Joined: Fri Jan 30, 2009 6:27 pm
Location: US

Re: Testing bits of a byte

Post by Jerry Messina » Tue Jun 16, 2015 9:52 am

The 8 inputs are independent and there's separate action to take depending on each pin.
Syntactically there's a couple of ways if doing this, but since in the end you need to handle 8 different conditions I don't think there's any real shortcut.

As long as the 'bits(x)' part has a const for 'x', like

Code: Select all

if (variable.bits(0) = 1) then
  <stuff>
endif
if (variable.bits(1) = 1) then
  <stuff>
endif
etc
then the code is about as short as it's going to get. If you had a variable in there for the bit index then things get a lot worse.

Jon Chandler
Registered User
Registered User
Posts: 185
Joined: Mon Mar 10, 2008 8:20 am
Location: Seattle, WA USA
Contact:

Re: Testing bits of a byte

Post by Jon Chandler » Tue Jun 16, 2015 2:02 pm

Thanks Jerry. Just wanted to make sure I wasn't overlooking some simple method!
Jon

Check out the TAP-28 PIC Application board at http://www.clever4hire.com/throwawaypic/

Post Reply