Programming Pearl 9 Chapter 7th obtain the number of 1 in a byte sequence

Source: Internet
Author: User

First, for each byte, obtain the number of 1 in this byte. Of course, the unsiged char value cannot be converted to the binary number, and then the number of 1 is counted. This method is very inefficient, this will think of bit operation, a good method of bit operation is to use the method of X & = X-1, how many times the calculation, how many 1, then for a byte, store the number of 1 in each number (0-255) into an array, so that the number of 1 in each byte can be directly found.

Int get_count (unsigned char X) {int COUNT = 0; while (x> 0) {X & = X-1; count ++;} return count ;} static unsigned char hash_table [256]; void pre_process (void) {unsigned char I; for (I = 0; I <256; I ++) hash_table [I] = get_count (I );}

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.