Bitwise operator with taking input from user

267 Views Asked by At
#include<stdio.h>

int main()
{
    unsigned char a,b;
   
    printf("Enter first number : ");
    scanf("%d",&a);
    printf("Enter 2nd number : ");

    scanf("%d",&b);
    printf("a&b = %d\n", a&b);

    printf("a|b = %d\n", a|b); 

    printf("a^b = %d\n", a^b);
    
    printf("~a = %d\n",a = ~a);
    printf("b<<1 = %d\n", b<<1); 

    printf("b>>1 = %d\n", b>>1); 

    return 0;
}

i am taking input from user but i am getting wrong output how i modify i***

error


1

There are 1 best solutions below

0
Vlad from Moscow On

These calls of scanf

scanf("%d",&a);

and

scanf("%d",&b);

use an incorrect format specification.

The variables a and b are declared as having the type unsigned char

unsigned char a,b;

If you want to enter integers in these variables you need to write

scanf("%hhu",&a);

and

scanf("%hhu",&b);

So your program will look like

#include <stdio.h>

int main( void )
{
    unsigned char a, b;

    printf( "Enter first number : " );
    scanf( "%hhu", &a );

    printf( "Enter 2nd number : " );
    scanf( "%hhu", &b );

    printf( "a&b = %d\n", a & b );

    printf( "a|b = %d\n", a | b );

    printf( "a^b = %d\n", a ^ b );

    printf( "~a = %d\n", a = ~a );

    printf( "b<<1 = %d\n", b << 1 );

    printf( "b>>1 = %d\n", b >> 1 );
}

The program output might look like

Enter first number : 10
Enter 2nd number : 15
a&b = 10
a|b = 15
a^b = 5
~a = 245
b<<1 = 30
b>>1 = 7