C language interview exercise questions, please write functions, exercise questions Function

Source: Internet
Author: User

C language interview exercise questions, please write functions, exercise questions Function

Question: Compile the Function

Unsigned int reverse_bits (unsigned int value );

The return value of this function is the value after the binary bitwise mode of value is changed from left to right. For example, on a 32-bit machine, the value 25 contains the following bits:

0000 0000 0000 0000 0000 0000 0001

The Return Value of the function should be 2550 136 832, and its binary bit is:

1001 1000 0000 0000 0000 0000 0000

There are two solutions below, both of which use the shift operation, but the second is more incisive.

The Code is as follows:

# Include
 
  
# Include
  
   
# Include
   
    
# Include
    
     
Unsigned int reverse_bit (unsigned int value) {unsigned int sum = 0; int I = 0; int bit = 0; for (I = 0; I <= 31; I ++) {bit = value & 1; sum + = bit * pow (2, (31-i); // pow (I, j) indicates I ^ j; value = value> 1;} return sum;} unsigned int reverse_bits (unsigned int value) {unsigned int answer; unsigned int I; answer = 0; /*** continue as long as I is not 0, which makes the loop irrelevant to the machine font length, thus avoiding the portability problem */for (I = 1; I! = 0; I <= 1) // control cycle count {answer <= 1; // shift answer left if (value & 1) {answer | = 1 ;} value >>=1; // value shifts to the right, one bit and one bit for comparison} return answer;} int main () {printf ("% u \ n ", reverse_bit (25); // call printf ("% u \ n", reverse_bits (25) for reverse_bits; // call return 0 for reverse_bits ;}
    
   
  
 

Related Article

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.