What are bitwise operators?

后端 未结 9 1794
闹比i
闹比i 2020-11-22 02:05

I\'m someone who writes code just for fun and haven\'t really delved into it in either an academic or professional setting, so stuff like these bitwise operators really esca

9条回答
  •  攒了一身酷
    2020-11-22 02:47

    In digital computer programming, a bitwise operation operates on one or more bit patterns or binary numerals at the level of their individual bits. It is a fast, primitive action directly supported by the processor, and is used to manipulate values for comparisons and calculations.

    operations:

    • bitwise AND

    • bitwise OR

    • bitwise NOT

    • bitwise XOR

    • etc

    List item

        AND|0 1        OR|0 1 
        ---+----      ---+---- 
          0|0 0         0|0 1 
          1|0 1         1|1 1 
    
       XOR|0 1        NOT|0 1 
       ---+----       ---+--- 
         0|0 1           |1 0 
         1|1 0
    

    Eg.

        203: 1100 1011
    AND  15: 0000 1111
    ------------------
      =  11: 0000 1011
    

    Uses of bitwise operator

    • The left-shift and right-shift operators are equivalent to multiplication and division by x * 2y respectively.

    Eg.

    int main()
    {
         int x = 19;
         printf ("x << 1 = %d\n" , x <<1);
         printf ("x >> 1 = %d\n", x >>1);
         return 0;
    }
    // Output: 38 9
    
    • The & operator can be used to quickly check if a number is odd or even

    Eg.

    int main()
    {
        int x = 19;
        (x & 1)? printf("Odd"): printf("Even");
        return 0;
     }
    // Output: Odd
    
    • Quick find minimum of x and y without if else statement

    Eg.

    int min(int x, int y)
    {
        return y ^ ((x ^ y) & - (x < y))
    }
    
    • Decimal to binary conversion

    Eg.

    #include 
    int main ()
    {
        int n , c , k ;
        printf("Enter an integer in decimal number system\n " ) ;
        scanf( "%d" , & n );
        printf("%d in binary number
        system is: \n " , n ) ;
        for ( c = 31; c >= 0 ; c -- )
        {
             k = n >> c ;
             if ( k & 1 )
                  printf("1" ) ;
             else
                  printf("0" ) ;
          }
          printf(" \n " );
          return 0 ;
    }
    
    • The XOR gate encryption is popular technique, because of its complixblity and reare use by the programmer.
    • bitwise XOR operator is the most useful operator from technical interview perspective.

    bitwise shifting works only with +ve number

    Also there is a wide range of use of bitwise logic

提交回复
热议问题