Most efficient way to read a bit from a byte?

What is the most efficient way to read a bit at a particular position in a byte?
one way is to & it with a suitably masked byte.
like (00111001 & 00000010) for reading the 2nd bit.
You could try using a union and a struct with specifically sized members
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>

union Byte
{
    unsigned char byte;

    struct
    {
        bool bit1 : 1;
        bool bit2 : 1;
        bool bit3 : 1;
        bool bit4 : 1;
        bool bit5 : 1;
        bool bit6 : 1;
        bool bit7 : 1;
        bool bit8 : 1;
    };
};

int main ()
{
    Byte b;

    b.byte = 0x65; // 0110 0101

    std::cout << b.bit8 << b.bit7 << b.bit6 << b.bit5 << ' '
              << b.bit4 << b.bit3 << b.bit2 << b.bit1 ;
}
0110 0101
Last edited on
Here's another option:
1
2
3
4
5
6
7
8
9
10
11
12
bool getBit(unsigned char byte, int position) // position in range 0-7
{
    return (byte >> position) & 0x1;
}

int main ()
{
    unsigned char b = 0x65; // 0110 0101

    std::cout << getBit(b,7) << getBit(b,6) << getBit(b,5) << getBit(b,4) << ' '
              << getBit(b,3) << getBit(b,2) << getBit(b,1) << getBit(b,0);
}
0110 0101


Shifting and masking are some of the simplest operations that a processor can handle, these are very fast and efficient.
Last edited on
Topic archived. No new replies allowed.