#include <stdio.h> void toBinary(int num); void toOct(int num); void toHex(int num); void total(int num, int base, int offset); void toBinary2(int num); void toOct2(int num); void toHex2(int num); int main(int argc, const char * argv[]) { toBinary(12); toOct(12); toHex(12); toBinary2(12); toOct2(12); toHex2(12); return 0; } void toBinary2(int num){ total(num, 1, 1); } void toOct2(int num){ total(num, 7, 3); } void toHex2(int num){ total(num, 15, 4); } void total(int num, int base, int offset) { char cs[16] = { '0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f' }; char rs[32]; int len = sizeof(rs) / sizeof(char); int pos = len; while (num) { int result = num & base; rs[--pos] = cs[result]; num = num>>offset; } for (int i = pos; i<len; i++) { printf("%c", rs[i]); } printf(" "); } // 转二进制 void toBinary(int num) { char cs[2] = {'0','1'}; char rs[32]; int len = sizeof(rs) / sizeof(char); int pos = len; // 32 while (num != 0) { int result = num & 1; rs[--pos] = cs[result]; num = num>>1; } for (int i = pos; i<len; i++) { printf("%c", rs[i]); } printf(" "); } // 转八进制 void toOct(int num) { char cs[8] = { '0','1','2','3','4','5','6','7' }; char rs[11]; int len = sizeof(rs) / sizeof(char); int pos = len; // 11; while (num != 0) { int result = num & 7; rs[--pos] = cs[result]; num = num>>3; } for (int i = pos; i<len; i++) { printf("%c", rs[i]); } printf(" "); } // 转十六进制 void toHex(int num) { char cs[16] = { '0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f' }; char rs[8]; int len = sizeof(rs) / sizeof(char); int pos = len; while (num != 0) { int result = num & 15; rs[--pos] = cs[result]; num = num>>4; } for (int i = pos; i<len; i++) { printf("%c", rs[i]); } printf(" "); }i
版权声明:本文为博主原创文章,未经博主允许不得转载。