C Language: Bit operation Small example several

Source: Internet
Author: User

First, I'll enumerate some of the commonly used operators associated with bit operations in C.


First, shift operators

Left shift operator <<

The arithmetic left shift and the logical left shift are all left-hand, and the right side is 0;

Right shift operator >>

The logical right moves to the right to the left of the highest bit 0, while the arithmetic right moves to the right to move out one bit, and the highest bit to fill the symbol bit.


Second, bitwise operators

and &

Algorithm: See 0 is 0, all 1 is 1;

or |

Algorithm: See 1 is 1, all 0 is 0;

Xor ^

Algorithm: The same 0, the difference is 1;


Next I'll share a few more common programming examples of bitwise manipulation


1. Do not use temporary variables to achieve the exchange of numbers a and b

#include <stdao.h>int main () {int a=2;aint b=3;a=a^b;b=a^b;a=a^b;printf ("a=%d,b=%d\n", A, b);     return 0;} 2. Do not use (A+B)/2 This way, the average value of two numbers #include <stdio.h>int fun (int x, int y) {Int ret  = 0;ret =  (X & y)  +  ((x  ^ y)  >> 1 );//printf ("%d\n",  ret);} Int main () {        int a, b;printf ("Please enter two number: \ n"); scanf_s ("%d %d",  &a, &b); fun (a, b); return  0;} 3. Find the number of 1 in the binary number//method one #include <stdio.h>int main () {         int x;int count=0;scanf_s ("%d",  &x);while  (x)     {         x = x& (x - 1);               count++;    }printf ("%D\n ", count); return  0;} Method two #include <stdio.h>int  count_one_bits (Int value)//  returns the number of bits of  1 {// 1111111111111111111int count = 0;int i = 0;    for (i =  0;i<32;i++) {if (value & 1 == 1) count++;value = value >>  1;} Return count;}

int main ()

{

printf ("%d\n", Count_one_bits (-1));

return 0;

}



This article is from the "Molova" blog, make sure to keep this source http://molova.blog.51cto.com/10594266/1684499

C Language: Bit operation Small example several

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.