CSAPP (1): Computer Representation of numbers-after-school questions, after-school csapp

Source: Internet
Author: User

CSAPP (1): Computer Representation of numbers-after-school questions, after-school csapp

2.65

Int even_ones (unsigned x)

Requirement: return 1 when x contains an even number of 1 s; 0 otherwise. Assume that int has w = 32 bits.

Analysis: the loop statement is not applicable. If you write a statement one by one, it will take 32 times; here, the operation is changed to logstores = 5 times. The bipartite method implies loop while simplifying loop traversal. How does one use the bipartite method?

The question is to judge the parity of 1 in x. We can divide x into 2. For example, if the first 16-bit x1 and the last 16-bit x2, x3 = x1 ^ x2, then, if x has an even number of 1, x3 must have an even number of 1; if x has an odd number of 1, x3 must have an odd number.

int even_ones(unsigned x){     x ^= (x >> 16);     x ^= (x >> 8);     x ^= (x >> 4);     x ^= (x >> 2);     x ^= (x >> 1);     return !(x & 1);    }

 

2.66

Int leftmost_one (unsigned x)

Requirements: generate mask indicating leftmost 1 in x. assume w = 32; if x = 0, then return 0;

Tip: Convert x into a bit vector like [0 .. 011 .. 1 ].

Analysis: here we look for the first bit of the highest bit of 1 in the vector x, we should use a loop, and then the loop is not available, here we use a bipartite. First, as in [tip], convert x to a bit vector like [0 .. 011 .. 1], that is, all the bits after the highest bit 1 are changed to 1.

int leftmost_one(unsigned x){     x |= x >> 1;     x |= x >> 2;     x |= x >> 4;     x |= x >> 8;     x |= x >> 16;     x &= ~(x >> 1);     return x;}

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.