C趣味程序百例(03)數(shù)制轉(zhuǎn)換

字號(hào):

10.數(shù)制轉(zhuǎn)換
     將任一整數(shù)轉(zhuǎn)換為二進(jìn)制形式
    *問(wèn)題分析與算法設(shè)計(jì)
     將十進(jìn)制整數(shù)轉(zhuǎn)換為二進(jìn)制的方法很多,這里介紹的實(shí)現(xiàn)方法利用了C語(yǔ)言能夠?qū)ξ贿M(jìn)行操作的特點(diǎn)。對(duì)于C語(yǔ)言來(lái)說(shuō),一個(gè)整數(shù)在計(jì)算機(jī)內(nèi)就是以二進(jìn)制的形式存儲(chǔ)的,所以沒(méi)有必要再將一個(gè)整數(shù)經(jīng)過(guò)一系列的運(yùn)算轉(zhuǎn)換為二進(jìn)制形式,只要將整數(shù)在內(nèi)存中的二進(jìn)制表示輸出即可。
    *程序說(shuō)明與注釋
    #include
    void printb(int,int);
    void main()
    {
     int x;printf("Input number:");
     scanf("%d",&x);
     printf("number of decimal form:%d\n",x);
     printf(" it's binary form:");
     printb(x,sizeof(int)*8); /*x:整數(shù) sizeof(int):int型在內(nèi)存中所占的字節(jié)數(shù)
     sizeof(int)*8:int型對(duì)應(yīng)的位數(shù)*/
     putchar('\n');
    }
    void printb(int x,int n)
    {
     if(n>0)
     {
     putchar('0'+((unsigned)(x&(1<<(n-1)))>>(n-1))); /*輸出第n位*/
     printb(x,n-1); /*歸調(diào)用,輸出x的后n-1位*/
     }
    }