In-depth understanding of computer system Second Edition After-school exercises 2.65

Source: Internet
Author: User

Write code to implement the following functions:

/* Return 1 when X contains an odd number of 1 s; 0 otherwise.

Assume W = 32 .*/

Int odd_ones (unsigned X );

Your function shocould follow the bit-level integer coding rules (page 120), could t that you may assume that data type int has W = 32 bits.

Your code shoshould contain a total of at most 12 arithmetic, bit-wise, and logical operations.

Answer:

Main principles used: 1. 1 ^ 1 = 1 0 ^ 0 = 0 1 ^ 0 = 1 0 ^ 1 = 1

2. Odd-even = odd, even-even = even

For unsigned X, the 16-bit height is different from the 16-bit lower, because 1 ^ 1 = 0, the number of 1 contained in 16 bits is exactly the number of 1 in X minus the even number. And so on, get a digit after the last XOR. If it is 1, it means that X contains an odd number of 1, and if it is 0, it means that X contains an even number of 1.

To reduce the number of operations, use Part X to save part B.

Int odd_ones (unsigned X) {// use the low 16 bits of X to represent B. x ^ A corresponds to B ^ A unsigned A = x> 16; X = x ^; // use the Lower 8 bits of X to represent B a = x> 8; X = x ^ A; // use the lower 4 bits of X to represent B A = x> 4; X = x ^ A; // use the low 2 bits of X to represent B A = x> 2; X = x ^; // use the low 1 bits of X to represent B A = x> 1; X = x ^ A; // at this time, returns X & 0x1 ;}

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.