3 ms·
Embedded applications use bitwise ops all the time. Particularly for performing changes to registers. Example, a microcontroller has an 8 bit status register.
by joshvm 13y ago
Embedded applications use bitwise ops all the time. Particularly for performing changes to registers.
Example, a microcontroller has an 8 bit status register. Each bit controls some hardware function. You wish to change bit 5, but you can't change anything else because it would cause unwanted side effects. So this rules out simply saying myregister = 0b00001000.
Common solution is to make a macro like:
#define setbit(BYTE,BIT) BYTE |= (1 << BIT)
Thus you can say I want to set bit 5 in my register by calling setbit(foo, 5) while keeping the rest of the byte intact. There are analogous macros for clearing and toggling bits.
Or you might want to perform an operation based on a particular bit in a byte, e.g. byte 5 is a status flag that tells you when a timer has overflowed.
#define getbit(BYTE, BIT) !!(BYTE & ~(1 << BIT))
Then you can say:
if( getbit(myregister, 5)){
// do something
}
Fun fun :)