Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdint.h>
- #include <string.h>
- #define SIZE(x) (sizeof(x) * 8)
- void int_to_binary(int num,uint8_t bin[],size_t n){
- size_t i=n-1;
- while(num){
- bin[i--]=num & 0x1;
- num>>=1;
- }
- }
- void print(uint8_t* bin,size_t n){
- for(size_t i=0;i<n;i++){
- printf("%d",bin[i]);
- if(i%4==0) printf(" ");
- }
- printf("\n");
- }
- size_t count_set_bits(int A,int B){
- size_t size = SIZE(int),s = size;
- uint8_t bin_A[size];
- uint8_t bin_B[size];
- memset(bin_A,0,size);
- memset(bin_B,0,size);
- int_to_binary(A,bin_A,size);
- int_to_binary(B,bin_B,size);
- uint8_t carry=0,count=0,sum=0;
- print(bin_A,size);
- print(bin_B,size);
- for(size_t bit=0;bit<=size;bit++){
- s--;
- sum = 0;
- for(size_t i=s,j=size-1;i<=size-1&&j>=s;i++,j--)
- sum+=bin_A[i]*bin_B[j];
- sum+=carry;
- count+=sum%2;
- printf("%d",sum%2);
- carry=(uint8_t)(sum/2);
- }
- s = size;
- for(size_t bit=0;bit<size;bit++){
- s--;
- sum=0;
- for(size_t i=0,j=s-1;i<s && j>=0;i++,j--)
- sum+=bin_A[i]*bin_B[j];
- sum+=carry;
- count+=sum%2;
- printf("%d",sum%2);
- carry=(uint8_t)(sum/2);
- }
- return count;
- }
- int main(){
- printf("%zu",count_set_bits(43749823,1232131));
- }
Add Comment
Please, Sign In to add comment