What is the most efficient way to read a bit at a particular position in a byte?

Recommended Answers

Here is a sample of code to test for a set bit. Adapt as necessary.

#include <stdio.h>
int main(void)
{
    unsigned char target_byte = 0x81;
    unsigned int i = 0; /* Always initialize variables - much safer! */
    for (i = 0x01; i <= 0x80; i = …
Jump to Post

All 4 Replies

By definition the byte is the smallest size object that can be addressed, so you have to read the whole byte and work with that.

Off the top of my head, I can't think of anything likely to be faster than the simple and obvious approach, particularly if the compiler can identify and optimise.

if (byte & 8) \\ i.e. if (byte & b00001000) - testing for bit marked one

Maybe someone has some super-fast cleverness, though.

Here is a sample of code to test for a set bit. Adapt as necessary.

#include <stdio.h>
int main(void)
{
    unsigned char target_byte = 0x81;
    unsigned int i = 0; /* Always initialize variables - much safer! */
    for (i = 0x01; i <= 0x80; i = (i << 1))
    {
        fprintf(stdout, "Reading bit %.02x\n", (unsigned char) i);
        if ((unsigned char)i & target_byte)
        {
            fprintf(stdout, "Bit %.02x is set\n", (unsigned char)i);
        }
    }
    return 0;
}

What is the most efficient way to read a bit at a particular position in a byte?

Amazingly enough, it depends on the bit in question. A general approach to reading any bit neglects tricks for reading specific bits more concisely (ie. using fewer instructions), and thus "faster".

Using the right shift (>>) operator is the quicker, if not the quickest, method.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.