Reading specific bits from an 8 bit binary number

Nov 4, 2015 at 8:08pm
I'm getting a return value in the form of an 8 bit binary number. For example:

10110010

I need a function that will tell me specifically which bits are high. So for the binary number above, which is decimal 178, I would need a function to take that value and spit back:

bit 7 is high
bit 5 is high
bit 4 is high
bit 1 is high

What's the best way to do this?
Nov 4, 2015 at 9:59pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <array>
#include <iostream>

bool bit_set(unsigned value, unsigned bit)
{
    return value & (1 << bit);
}

void check_bit(unsigned value, unsigned bit)
{
    std::cout << "bit " << bit << " is " << (bit_set(value, bit) ? "set" : "not set") << '\n';
}

int main()
{
    unsigned value = 178;

    std::array<unsigned, 4> bits = { 7, 5, 4, 1 };

    for (auto bit : bits)
        check_bit(value, bit);
}
Nov 4, 2015 at 10:10pm
What do you mean by
spit back:

bit 7 is high
bit 5 is high
bit 4 is high
bit 1 is high
Nov 5, 2015 at 2:38am
Cire,

I see what you did with check_bit but I was using 10110010 as an example. I need this to work for any binary value. In main you have specifically put 7,5,4,1 into the array. How can I put each bit into the array for any binary value I receive?
Nov 5, 2015 at 3:04am
kbw, it seems to mean that that specific bit is 1.
Nov 5, 2015 at 1:45pm
If your decimal number 178 is an int32, you could use std::bitset<32>.
See http://www.cplusplus.com/reference/bitset/bitset/
Nov 5, 2015 at 2:28pm
Yeah, but there's no point thinking about it unless the Op can say what input and output he needs.

I'm sure he doesn't want a function that writes text to stdout, that'd be silly; or maybe he does. He's managed to say he wants to pass in any integral value after someone posted a solution, ... see what I mean?
Nov 5, 2015 at 3:13pm
I see what you did with check_bit but I was using 10110010 as an example. I need this to work for any binary value.

It works for any value that meets the constraints in the OP.



In main you have specifically put 7,5,4,1 into the array. How can I put each bit into the array for any binary value I receive?

The bits in the array are the bits to check. Change what's in the array to change which bits you're checking (or don't even use the array.) The code in main is just demonstration.
Nov 5, 2015 at 6:23pm
I think you're looking for this:
1
2
3
4
5
6
7
8
void showbits(unsigned num)
{
    for (int bit=31; bit >= 0; --bit) {
	if (num & (1U << bit)) {
	    cout << "bit " << bit << "is high\n";
	}
    }
}
Topic archived. No new replies allowed.