1. 程式人生 > >C語言學習(四)

C語言學習(四)

vc++ gin margin 結果 com 語言學 http std oid

面試題中二進制轉換問題,將一個二進制數,從某位開始進行,n位轉換,程序如下所示:

 1 /************************************************************************/
 2 /* 功能:實現二進制數X的轉化,p為轉化位數,n為轉化長度。例x=0b0001 0001,p=4,n=3轉換後x=0b0110 0001
 3 /* 作者:ZL
 4 /* 日期:2018-04-08   14:38                                                                 
 5 /***********************************************************************
*/ 6 7 #include <stdio.h> 8 9 unsigned int convert(unsigned int x,int p,int n); 10 void D_TO_B(unsigned int x); 11 12 13 int main(void) 14 { 15 16 unsigned int x=17; 17 unsigned int y; 18 19 printf("轉換前:"); 20 D_TO_B(x); 21 printf("\n"); 22 23 y=convert(x,4,3); 24
printf("轉換後:"); 25 D_TO_B(y); 26 printf("\n"); 27 28 29 30 } 31 32 33 unsigned int convert(unsigned int x,int p,int n) 34 { 35 unsigned int Bit=0; 36 unsigned int temp=1; 37 int i=0; 38 39 for (i=0;i<n;i++) 40 { 41 Bit |=temp; 42 temp<<=1
; 43 } 44 45 Bit=Bit<<p; 46 x ^=Bit; 47 return x; 48 } 49 50 void D_TO_B(unsigned int x) 51 { 52 int i=0,j=0; 53 if (x==0) 54 { 55 return; 56 } 57 else 58 { 59 i=x%2; 60 j=x/2; 61 D_TO_B(j); 62 printf("%d",i); 63 } 64 }

程序在VC++6.0中運行結果如下圖所示:

技術分享圖片

C語言學習(四)