Tips and tricks for embedded C programming

Bit swap in byte, per this useful article

uint8_t byte_reverse (uint8_t x) {
    x = (x >> 4) | (x << 4);
    x = ((x & 0xcc) >> 2)|((x & 0x33) << 2);
    x = ((x & 0xaa) >> 1)|((x & 0x55) << 1);
    return x;
}

Conditional error messages. Sometimes there is need for debug output with different parts of string text, depending on input condition test.

#define SELF_TEST_FAIL               1

uint8_t selftest = 0;                // Self-test value
char resstr[15];                     // Char string for values
strncpy(&resstr[0],"PASS \r\n",7);   // This is good result text
strncpy(&resstr[8],"FAIL \r\n",7);   // This is fail result text

// Some code here to update selftest value...

Line below prints either PASS or FAIL message, depends on condition selftest == SELF_TEST_FAIL

printf ("\033[0;35m-i- Test result ....... %.*s", 7, (selftest == SELF_TEST_FAIL) ? &resstr[8] : &resstr[0]);

%.*s used to output only seven characters from the string address.

Setting a bit

Use the bitwise OR operator (|) to set a bit.

number |= 1 << x;

That will set bit x.

Clearing a bit

Use the bitwise AND operator (&) to clear a bit.

number &= ~(1 << x);

That will clear bit x. You must invert the bit string with the bitwise NOT operator (~), then AND it.

Toggling a bit

The XOR operator (^) can be used to toggle a bit.

number ^= 1 << x;

That will toggle bit x.

Checking a bit

To check a bit, shift the number x to the right, then bitwise AND it:

bit = (number >> x) & 1;

That will put the value of bit x into the variable bit.

Changing the nth bit to x

Setting the nth bit to either 1 or 0 can be achieved with the following:

number ^= (-x ^ number) & (1 << n);

Bit n will be set if x is 1, and cleared if x is 0.

Projects like this are born from passion and a desire to share how things work. Education is the foundation of a healthy society - especially important in today's volatile world. xDevs began as a personal project notepad in Kherson, Ukraine back in 2008 and has grown with support of passionate readers just like you. There are no (and never will be) any ads, sponsors or shareholders behind xDevs.com, just a commitment to inspire and help learning. If you are in a position to help others like us, please consider supporting xDevs.com’s home-country Ukraine in its defense of freedom to speak, freedom to live in peace and freedom to choose their way. You can use official site to support Ukraine – United24 or Help99. Every cent counts.

Author: Ilya Tsemenko
Created: Jan. 8, 2016, 7:24 a.m.
Modified: June 7, 2025, 11:54 a.m.

References