Reputation: 181
I am wanting to write to a register.
The register holds 1 byte of information. I wish to change bit 6 for argument's sake.
The way I am accomplishing this right now is to read the register, then do a set/clear.
This way I only change the bit I am interested in, and leave the rest untouched.
E.g.:
// Read register
uint8_t reading = read_reg(0x00);
// Set 6th bit
if (wanting_to_set) { reading |= (1 << 6); }
if (wanting_to_reset) { reading &= ~(1 << 6); }
// Write back to register
write_reg(0x00, reading);
Is there a way I can set or reset the nth bit without knowing that the byte is? This way I can avoid having to read the register first.
Upvotes: 2
Views: 569
Reputation: 181034
Is there a way I can set or reset the nth bit without knowing that the byte is? This way I can avoid having to read the register first.
There is no standard way to perform such a thing in C. Even in the event that you have a machine with individually addressable bits, the C language does not define any means of accessing memory in units smaller than 8 bits, no matter what the capabilities of the underlying hardware.
Therefore, in standard C, if you want to modify an individual bit without modifying any of the other bits nearby then you must accomplish it by at the same time overwriting at least seven bits near that one with the same values they already have. That means you must either have the current values of those bits or not care what values are written to them.
Upvotes: 4
Reputation: 67820
As an addition to @John's answer:
Very popular ARM Cortex-M(3,4) uCs have bit-banding memory area. All bits in this area are individually addressable. So you can simply read or write one bit by simple resing or writing to that address.
Upvotes: 3