求一个数的二进制代码、八进制代码和十六进制代码(范围-2147483648~2147483647)

/*求一个数的二进制代码、八进制代码和十六进制代码(范围-2147483648~2147483647)*/ #include <stdio.h> #include <math.h> #define BITNUM 32 void MyBinaryPlusOne(int a[]); void MyBinaryReverse(int a[]); void OutMyBinary(long a,int b[]); void OutMyOctonary(int a[]); void OutMyHex(int a[]); int main(void) { long MyInt = 0; int Binary[BITNUM],i;/*存放MyInt的二进制码*/ while(1) { for(i = 0; i<BITNUM; i++) Binary[i] = 0; /*将数组清零*/ printf("/n/nInput integer:"); scanf("%ld",&MyInt); /*输入长整形时使用输入控制符号"%ld"*/ /*printf("%ld/n",MyInt);输出长整形时使用输入控制符号"%ld"*/ OutMyBinary(MyInt,Binary); OutMyOctonary(Binary); OutMyHex(Binary); printf("/n/nExit(ESC),other keys continue..."); if(getch() == 27) break; } return 0; } void OutMyBinary(long a,int Binary[BITNUM]) { int i; long b = labs(a); for(i = BITNUM - 1; b > 1 && i >= 0;i--) { /*printf("%d",b%2);*/ Binary[i] = b%2; b/=2; } Binary[i] = b; printf("/nBinary:"); if( a > 0) { for(i = 0; i < BITNUM; i++) { printf("%d",Binary[i]); } } else { MyBinaryReverse(Binary);/*取反*/ printf("/n"); MyBinaryPlusOne(Binary);/*加1*/ for(i = 0; i < BITNUM; i++) { printf("%d",Binary[i]); } } } void MyBinaryPlusOne(int a[BITNUM]) { int i; for(i = BITNUM -1; i >= 1; i--) { a[i] = ((a[i] + 1) == 2)?0:1; if(a[i] == 0) continue; else break; } } void MyBinaryReverse(int a[BITNUM]) { int i; for(i = 0; i < BITNUM; i++) { a[i] = 1 - a[i]; } } void OutMyOctonary(int a[BITNUM]) { int i,j; int octonary = 0; int b[(BITNUM+1)/3] = {0}; for(i = 0,j = 0; i < BITNUM; i++,j++) { int Item = 0; Item = a[BITNUM - (i + 1)]; octonary += Item*pow(2,j%3); if((j+1)%3 == 0) { b[(i+1)/3 - 1] = octonary; /*printf("%d",octonary);*/ j = -1; octonary = 0; } if(i == BITNUM - 1) { b[(BITNUM+1)/3 - 1] = octonary; } } printf("/nOctonary:"); for(i = (BITNUM+1)/3-1; i>=0; i--) { printf("%d",b[i]); } } void OutMyHex(int a[BITNUM]) { int i,j; int hex = 0; char b[BITNUM/4] = {'/0'}; for(i = 0,j = 0; i < BITNUM; i++,j++) { int Item = 0; Item = a[BITNUM - (i + 1)]; hex += Item*pow(2,j%4); if((j+1)%4 == 0) { switch(hex) { case 15: b[(i+1)/4 -1] = 'F';break; case 14: b[(i+1)/4 -1] = 'E';break; case 13: b[(i+1)/4 -1] = 'D';break; case 12: b[(i+1)/4 -1] = 'C';break; case 11: b[(i+1)/4 -1] = 'B';break; case 10: b[(i+1)/4 -1] = 'A';break; default: b[(i+1)/4 -1] = (char)(hex + 48); } /*printf("%d",octonary);*/ j = -1; hex = 0; } } printf("/nHex:"); for(i = BITNUM/4-1; i>=0; i--) { printf("%c",b[i]); } }  

你可能感兴趣的:(c,Integer,hex)