Setting bits based on a count?

Thread Starter

spinnaker

Joined Oct 29, 2009
7,830
For some reason I can't figure this one out.

Say I have a for loop

Rich (BB code):
for (int i=0; i<=3; i++)
{
     setBits(i);

}
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?
 

ke5nnt

Joined Mar 1, 2009
384
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?
 

MrChips

Joined Oct 2, 2009
35,114
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!
 

THE_RB

Joined Feb 11, 2008
5,438
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.)
 

Thread Starter

spinnaker

Joined Oct 29, 2009
7,830
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.)
This is basically what I do now.
 
Top