Setting bits based on a count?

Discussion in 'Embedded Systems and Microcontrollers' started by spinnaker, Mar 29, 2013.

1. spinnaker Thread Starter AAC Fanatic!

Oct 29, 2009
5,063
1,160
For some reason I can't figure this one out.

Say I have a for loop

Code ( (Unknown Language)):
1.
2. for (int i=0; i<=3; i++)
3. {
4.      setBits(i);
5.
6. }
7.
Say my SFR has a value of 0b11000100

How would I set the value of the 4 and 5th bits to the value of i?

2. ke5nnt Active Member

Mar 1, 2009
384
15
You are wanting to change just bits 4 and 5 of the SFR to equal i every time it increments? So your bit sequence would look like:
11000100
11010100
11100100

Is that correct?

3. ErnieM AAC Fanatic!

Apr 24, 2011
7,434
1,625
Make a hole, slip in the bits:

SFR = (SFR & 0b11001111) | (i << 4);

4. spinnaker Thread Starter AAC Fanatic!

Oct 29, 2009
5,063
1,160
Ah so I clear those bits first then set them?

5. MrChips Moderator

Oct 2, 2009
12,623
3,451
Take i and shift it left by 4 bits
(i << 4)

Take SFR and mask bits 4 and 5
(SFR & 0xCF)

then OR the shifted bits
(SFR & 0xCF) | (i << 4)

Edit: ErnieM beat me to it!

6. THE_RB AAC Fanatic!

Feb 11, 2008
5,435
1,305
The smallest and fastest compiled code may be from using bit tests;

sfr.F4 = 0;
if(i.F0) sfr.F4 = 1;
sfr.F5 = 0;
if(i.F1) sfr.F5 = 1;

(If your C compiler is one of those poor ones that doesn't allow bit testing/setting then you may not have that option.)

7. spinnaker Thread Starter AAC Fanatic!

Oct 29, 2009
5,063
1,160
This is basically what I do now.

8. Markd77 Senior Member

Sep 7, 2009
2,803
594
If the compiler optimises i<<4 as the swapf instruction then that would be pretty fast too.