天天看點

Bitwise Operation Explained

原文連結:Bitwise Operation Explained

1.統計一個數置位為1的個數

複制代碼

#include <stdio.h>

int __numOf_SET_Bits(int var)

{

    if (var==0) return 0;

    else return (var&01)?1+__numOf_SET_Bits(var>>1):__numOf_SET_Bits(var>>1);

}

int main()

    int var=128;

    printf("Num of Bits: %d\n",__numOf_SET_Bits(var));

    return 0;

2,判斷一個數是奇數還是偶數

#define isEven(a) ((((a)&01)==0)?1:0)

    int var=1;

    if(isEven(var))

    {

        printf("%d is a even number \n",var);

    }

    else

        printf("%d is a odd number \n",var);

方法二:

#define isEven(a) ((((a)%2)==0)?1:0)

    int var=11;

3,判斷一個數是否是2的幂次方

#define __isPower_of_TWO(a) (((a)&(a-1))==0)?1:0

    int arr[] = {1,2,3,4,5,8,9,16};

    int i=0;

    for(;i<sizeof(arr)/sizeof(arr[0]);i++)

        if (__isPower_of_TWO(*(arr+i)))

            printf("%d has a form of Power of Two \n",*(arr+i));

        else

            printf("%d is not in the form \n", *(arr+i));

#define __isPower_of_TWO(a) (((a)&(-a))==a)?1:0

方法三:

 複制代碼

#include <stdlib.h>

        if (__numOf_SET_Bits(arr[i])==1)

    system("pause");

4,不使用第三個數,交換兩個數

void __SWAP(int *a,int *b)

    *a = *a ^ *b;

    *b = *a ^ *b;

    int a=5, b=6;

    printf("Before swap: a=%d <=====> b=%d \n",a,b);

    __SWAP(&a,&b);

    printf("After  swap: a=%d <=====> b=%d \n",a,b);

5,異或雙向連結清單

#include <assert.h>

typedef struct XOR_based_Node 

    int data;//資料域

    unsigned long compressedAddress;

}node;

node* head = NULL;//異或雙向連結清單表頭

void add_element_to_list(node** headRef, int data)

{//插入表頭

    node *newNode = (node*)malloc(sizeof(node));

    assert(newNode);

    newNode->compressedAddress = (unsigned long)(*headRef);

    newNode->data = data;

    if(*headRef != NULL)

        (*headRef)->compressedAddress ^= (unsigned long)newNode;

    *headRef=newNode;

void printList(node* head)

{//輸出表

    unsigned long prev = 0;

    while(head)

        unsigned long next = prev ^ head->compressedAddress;

        printf("%d ", head->data);

        prev = (unsigned long)head;

        head = (node *)next;

    printf("\n");

int main(void) 

    for(;i<10;i++)

        add_element_to_list(&head,i);

    printList(head);

本文轉自Phinecos(洞庭散人)部落格園部落格,原文連結:http://www.cnblogs.com/phinecos/archive/2008/08/22/1273784.html,如需轉載請自行聯系原作者