C-bit operation implements function body

Source: Internet
Author: User

/*1, a bitwise operation for the multiplication of unsigned integers, the function prototype is unsigned int multiply (unsigned int x, unsigned int y);. For example: (11011) 2x (10010) 2= ((11011) 2<<1) + ((11011) 2<<4). (unsigned int occupies 4 bytes, a total of 32 bits) */#include unsigned int multiply (unsigned int a,unsigned int b) {int c =0,i = 0; for (; I < 32;i + +) {if (b&1)//To determine if the lowest bit is 1 { c = C + (a << i);//Move I-bit add b>>=1;//b right 1 bit} else {b>>=1;}} return c;} int main () {unsigned int x, y; printf ("Please input x and y value:"); scanf ("%u%u", &x,&y); printf ("Auto implementation:%d*%d=%d\n", x,y,x*y); printf ("Function implementation:%d*%d=%d\n", x, y, multiply (x, y)); return 0;} /*2, a 32-bit unsigned integer loop right, the function prototype is unsigned int rotate_right (unsigned int x, int n); the so-called loop right shift is to put the low-displacement part up to the high position, for example, Rotate_right ( The value of 0xdeadbeef, 8) should be 0xefdeadbe. */#include unsigned int rotate_right (unsigned int x, int n), int main () {unsigned int x; int n; printf ("Please input x and N: "); scanf ("%u%d", &x,&n); printf ("x:%u\n", Rotate_right (x, n)); return 0;} unsigned int rotate_right (unsigned int x, int n) {for (int i = 0;i < n; i + +)//loop N-bit {if (x&1)//To determine if the lowest bit is 1 if 1 moves to the most High, highest bit plus 1 {x = x >> 1; x = x + 0x80000000;//x+=1<<31;} else {x = x >> 1;}} return x;}

C-bit operations implement function body

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.