ironhide391
ironhide391

Reputation: 595

Can anyone explain why am i getting the same result for bitwise and and or operator in C

I want flip the lsb of uint from 1 to 0 and vice-versa Can someone tell me why the below code is o/p the same result of & and | operation.

#include<stdio.h>
#include<stdint.h>
int main()
{
    uint8_t a=53;
    uint8_t x=255; //     AND BY 255 TO insert 0 at LSB position 11111110
    uint8_t y=1;   //      OR BY   1 TO insert 1 at LSB position 00000001

    uint8_t b=a&x;
    uint8_t c=a|y;

    printf("\nValue of byte a : %d",a );
    printf("\nValue of byte b : %d",b );
    printf("\nValue of byte c : %d",c );
    getchar();
    return 0;
}

How can the value of a, b and be the same, i.e. 53 I am using Pelles C IDE

Upvotes: 2

Views: 193

Answers (5)

huseyin tugrul buyukisik
huseyin tugrul buyukisik

Reputation: 11926

You should learn some de-Morgan rules

X and 1 = X
X and 0 = 0
X or  1 = 1
X or  0 = X
X xor 0 = X
X xor 1 = not X   ---> this is the flipping so you need Var^1   (^means xor)
not ( X and Y) = (not X) or (not Y)
not ( X or Y ) = (not X) and (not Y)
X or Y = not ( (not X) and (not Y) )

Where X is the lsb of your variable.

Also 255's lsb is 1 and 1's lsb is also 1

So,

53 & 255 => lsb=1 because both lsb's are 1 
53 | 1 => lsb=1 because any one of the lsb's are 1

If you want to flip the lsb, then only lsb of the second operand need to be 1 if you use xor

Var ^ 1 ==>flips the lsb of Var

If you need to flip using only and , not and or , then you need to use x3 or x4 more calculations(not efficient) and this is left to you as an excersize.

Upvotes: 2

Let's write out the numbers in binary:

        a = 00010011
        x = 11111111
        y = 00000001
b = a & x = 00010011
c = a | y = 00010011

The bitwise or of y and a is a, since the least significant bit of a is already 1.

The bitwise and of x with any 8-bit number is that same 8-bit number, since all the bits of x are 1. If you want to set the least significant bit to 1, you need to take the bitwise and with 11111110 binary = 254 decimal. Rather than write it out, you can use the ~ bitwise operator to make the calculation.

uint8_t x = ~1;
uint8_t b = a & x;

Upvotes: 2

user529758
user529758

Reputation:

53 in binary: 00110101

255 in binary: 11111111

1 in binary: 00000001

So,

a & x = 00110101 & 11111111 = 00110101 = 53

and

a | y = 00110101 | 00000001 = 00110101 = 53

Upvotes: 2

Rohan
Rohan

Reputation: 53386

255 is 11111111 in binary. You want 254 ie 11111110. ?

Upvotes: 3

Tom Tanner
Tom Tanner

Reputation: 9354

How to you expect to insert a 0 at the LSB by anding with all ones?

Upvotes: 2

Related Questions