1. ## Setting bits

How would I set xth bit in a int j?

All i can think of is something like this:

#define FIRST 0x00000001
#define SECOND 0x00000010
#define THIRD 0x00000100
#define FOURTH 0x00001000

#define BIT_TO_SET 4

int j = 0;

switch ( BIT_TO_SET ) {
case 1: j |= FIRST;
break;
case 2: j |= SECOND;
break;
case 3: j |= THIRD;
break;
case 4: j |= FOURTH;
case etc...
}

Is there a better or more effiecent way to set individual bits based on a int? This is for a PIC so every cycle counts and what I've got just seems a little clunky.

Cheers

2. Code:
```dec         bin
1             1
2             10
3             11
4             100
...
8             1000```
See a pattern? You can OR it with 2^n to set the nth bit

3. can you give an example?

if i wanted to:

2 ^ n
2 ^ 3 // assume n is 3 so we can set the third bit
10 ^ 11 // binary
01 // result

that would set the first bit, I dont think I am understanding

4. Actually theres probably a better way...I'm thinking bitshift:
Code:
```int SetBit(int j, int bit)
{
return  j|=(1<<bit);
}```
Something like that anyways...

5. Maybe I should explain better because I'm not doing good at helping you so far heh.

That would simply OR whatever number you have with whatever bit you want to set (starting at zero, keep in mind)

The bitshift moves the number one digit, in binary, to the left
So 1<<0 = 1 (1 in binary)
1<<1 = 2 (10 in binary)
1<<2 = 4 (100 in binary)
1<<3 = 8 (1000 in binary)

You can also use shift right (>>) similarly

If you don't know how to convert between decimal and binary (and other bases for that matter) now is a good time to learn

6. oh how i love bit shifting

7. You may also want to check out bitfields

Code:
```#define ON  1
#define OFF 0

typedef struct _Flags
{
unsigned int bit1 : 1;
unsigned int bit2 : 1;
unsigned int bit3 : 1;

} Flags;

Flags f;
f.bit1 = ON;```
Not normal practice, but a nifty idea I thought up, if I do say so myself =). Of course, I wouldn't normally do something like this, I'd #define the value of single bits before using this.

8. ah, i see

Thanx heaps dude that was a really helpful explanation and I have achieved what I wanted!!

9. Just looked at bitfields, that may come in handy when the prog gets a bit bigger, thanks

10. Perhaps a few handy macros are in order:
Code:
```#define bit(i)      (1UL << (i))
#define set(x, i)   (x |= bit(i))
#define clear(x, i) (x &= ~bit(i))
#define test(x, i)  (x & bit(i))```
This saves you from having to remember how to do what and avoids somewhat ugly code.