0

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

5
Contributors
4
Replies
35
Views
4 Years
Discussion Span
Last Post by RonalBertogi
0

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.

Edited by Moschops

1

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;
}
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".

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.