How to check each bit in a binary number?? - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!


How to check each bit in a binary number??

215215 Posts: 1Member
edited March 2014 in Beginner C/C++

I am looking for a method where i only by using And,OR and so on, can check each bit in a binary number, since each bit has it own instruction, it has to be interpreted in a certain way.
I would Normally have included all kind libraries to make such thing happen, but since it has to be done using arithmetically..

this is what i've managed to do so far..

void checkBit (binary_value)
    if((binary_value<<7) == 1)
    binary_value1 &= ~(0b00000001 << 7);
    binary_value1 |= (0b00000001 << 7);

        if((binary_value<<6) == 1)
        binary_value1 &= ~(0b00000001 << 6);
        binary_value1 |= (0b00000001 << 6);

            if((binary_value<<5) == 1)
            binary_value1 &= ~(0b00000001 << 5);
            binary_value1 |= (0b00000001 << 5);

                if((binary_value<<4) == 1)
                binary_value1 &= ~(0b00000001 << 4);
                binary_value1 |= (0b00000001 << 4);

                    if((binary_value<<3) == 1)
                    binary_value1 &= ~(0b00000001 << 3);
                    binary_value1 |= (0b00000001 << 3);

                        if((binary_value<<2) == 1)
                        binary_value1 &= ~(0b00000001 << 2);
                        binary_value1 |= (0b00000001 << 2);

                            if((binary_value<<1) == 1)
                            binary_value1 &= ~(0b00000001 << 1);
                            binary_value1 |= (0b00000001 << 1);

                                if((binary_value<<0) == 1)
                                binary_value1 &= ~(0b00000001 << 0);
                                binary_value1 |= (0b00000001 << 0);


This is what i've managed to do so far.. but i am wondering if it is correctly made?
Because my program isn't working properly, so it's either this code piece or something else in my code..



  • Gregry2Gregry2 Posts: 607Member

    First off, C doesn't have have binary literals, so 0b0001 is not a number. You have to either use just 1 or 0x01 which is hexadecimal. Moreover, whenever you have code that looks repetitive save for a single number that is different, think about using a for loop.

    Also, I'm not sure what you're attempting to do. Am I correct in assuming that your trying to invert binary_value and store it in binary_value1 (which you haven't declared yet)?

Sign In or Register to comment.