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...
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...
Using the bit operators of |, &, or ^, depending on what it is you are trying to do.
Uhhmmm. I'm assuming you are confusing a bit with a byte here?
actually I'm not
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
Last edited by Tiago; 04-17-2010 at 05:52 PM.
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.)
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.
Last edited by grumpy; 04-17-2010 at 06:15 PM.
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...
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:
Or if you want to reset the bit:Code:REGISTER |= (1 << PIN_POSITION)
Code:REGISTER &= ~(1 << PIN_POSITION)
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.