Number of 1 in a binary number

Source: Internet
Author: User

Write a function to return the number of 1 in a parameter binary

For example: 15 0000 1111 4 x 1

Program prototypes:

int count_one_bits (unsigned int value)

{

Returns the number of digits in 1

}

Method one: (modulo) disadvantage; The case that the decimal is negative is not considered, example 1 bit=0#include<stdio.h> #include <stdlib.h>int main () {int count = 0;int num =-1 ; scanf ("%d", &num), while (num) {if (num% 2 = = 1) {count++;} num = NUM/2;} printf ("count=%d\n", count); System ("pause"); return 0;}

Method Two: (Bitwise AND and SHIFT)

int main () {int count = 0;int num = 15;int i = 32;while (i) {if (num & 1 = = 1) {count++;} num = Num/2;num = num >> 1;i-= 1;} printf ("count=%d\n", count); System ("pause"); return 0;}


Method Three: (x=x& (x-1))

#include <stdio.h> int main () {int count = 0;int num = 0;scanf ("%d", &num), while (num) {count++;num = num & (num -1);//Number of 1}printf ("Count =%d\n", count); return 0;}

Report:

(1) num=x& (x-1) to determine whether it is 2^n, then num= (num-1) &num is 00

(2) int count_one_bits (unsigned int value), positive number does not need to consider complement, negative number need to consider complement,

unsigned int value is clever in that negative numbers can also be used


This article is from the "Little Gray Ash" blog, please make sure to keep this source http://10742910.blog.51cto.com/10732910/1719787

Number of 1 in a binary number

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.