分类: C/C++
2010-09-07 01:27:46
将任意正整数转换为四进制或八进制数。
刘峰六:
(1) 请小心一个问题,对于8禁止,相当于3位一段,32位是不能被三整除的,也就会导致结果不正确
(2) 对于1111111000011这样的数字,如果数字式正数,如果前面补足N个0,那么其实数字的大小是不变的,所以这里我传入了sizeof(int)+1,也就是33
但是如果是负数,那么只有2,4进制是正确的,因为它们不需要补位,但是对于8进制的话,如果开始是1,表示的是负数,那么就会涉及符号位的问题
是补零还是补充一是不一定的,不同的编译器有着不同的处理,有的补1,有的补0(见《C语言教程》-- 谭浩强,昨儿刚查滴… … )(因为int是32位,所以
永远是2和1滴倍数)
(3) 本体米有涉及16进制,涉及了也很简单,只要多个大于10就用 ‘A’ + ((unsigned )(x&(1<<(n-1))) >>(n-1))); 就OK了,因为32也是4的倍数,所以
还是八进制最复杂~~~~~~~
1:
2: /*
3: * A converter for Decimal to Binary Quaternary or Octal
4: */
5:
6: #include
7:
8: void printbin(int, int);
9: void printQuater(int,int);
10: void printOtc(int,int);
11:
12: int main(void)
13: {
14: int x;
15: printf("Input Number: ");
16: scanf("%d", &x);
17:
18: //Binary
19: printf("it's binary form: ");
20: printbin(x, sizeof(int)*8);
21: putchar('\n');
22:
23: //Quaternary
24: printf("it's Quaternary form: ");
25: printQuater(x, (sizeof(int)*8));
26: putchar('\n');
27:
28: //OTC
29: printf("it's Otc form: ");
30: printOtc(x, (sizeof(int)*8+1));
31: putchar('\n');
32:
33: return 0;
34: }
35:
36: //Binary
37: void printbin(int x, int n)
38: {
39: if(n>0)
40: {
41: putchar('0'+((unsigned) ( x & (1 << (n-1))) >> (n-1)));
42: printbin(x,n-1);
43: }
44: }
45:
46:
47: // Quaternary
48: void printQuater(int x,int n)
49: {
50: if(n>0)
51: {
52: putchar('0'+ ((unsigned)( x & ( 3 << (n-2))) >> (n-2) ) );
53: printQuater(x,n-2);
54: }
55: }
56:
57: //Octal
58: void printOtc(int x, int n)
59: {
60: if(n>0)
61: {
62: putchar('0'+ ((unsigned)( x & ( 7 << (n-3))) >> (n-3) ) );
63: printOtc(x,n-3);
64: }
65:
66: }
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/asiainfolf/archive/2010/09/07/5867499.aspx