# Thread: Changing a single bit of an integer

1. ## Changing a single bit of an integer

I've created a 4 bits Int... I want to change only one of the 4 bits of this Int, how do I do that?

ty...

2. Using the bit operators of |, &, or ^, depending on what it is you are trying to do.

3. Uhhmmm. I'm assuming you are confusing a bit with a byte here?

4. Originally Posted by claudiu
Uhhmmm. I'm assuming you are confusing a bit with a byte here?
actually I'm not

Code:
`unsigned int type:4;`

Originally Posted by tabstop
Using the bit operators of |, &, or ^, depending on what it is you are trying to do.
I'm not seeing how I'm going to change a single bit from the bit-word without adding too many logic to the program (I hate logic, even more if it's 1 AM), instead I'm going to use four 1-bit words... ty

5. If you never need the value as a single coherent thing then that will work marvelously. (I'm not sure how using an operator is "too much logic", but you've certainly got the edge in readability.)

6. Originally Posted by Tiago
Code:
`unsigned int type:4;`
I'm not seeing how I'm going to change a single bit from the bit-word without adding too many logic to the program (I hate logic, even more if it's 1 AM), instead I'm going to use four 1-bit words... ty
Well, logic is the only practical choice you have. Single upset events, while having the ability to change the value of single bits regardless of your program logic, are generally considered a little too unpredictable for practical application.

You will need to copy your 4 bit int into a normal unsigned variable, manipulate the 4 bits of that variable, and copy the result back into your 4 bits.

Bitfields, such as you are using, are mostly used to represent smaller value ranges (eg a 4 bit unsigned bitfield can represent values in the range 0 to 15), not for playing with individual bits.

Keep in mind that the organisation of bitfields within a type are implementation defined.

7. The SNIPPETS C collection - file:

All you need mate; thinking not required but you might find thought useful if you get into programming on any serious level...

8. This is very common when doing embedded programming. Many systems define macros of all the pins as the position from the right, so you can use shifts to single out a single bit. For example, if you want to set a specific bit in a register:

Code:
`REGISTER |= (1 << PIN_POSITION)`
Or if you want to reset the bit:
Code:
`REGISTER &= ~(1 << PIN_POSITION)`

9. Ok, thank you all...

I've never been taught how to use bit operations and logic in C, but despite that (I'm going to have to learn it sooner or later), I'm going to spend some time trying to use this in my program, it doesn't seem that difficult, also.