发个话题大家讨论讨论(数的进制转换)
![](images/smilies/emot/em25.gif)
#include <iostream> #include <vector> using namespace std; void convert(int x, int n, int m) { vector vi; int y; while(x) { y = x % m; vi.push_back(y); x /= m; } vector::reverse_iterator rit = vi.rbegin(); for( ; rit!=vi.rend(); rit ) { if( *rit >= 10 ) { char temp = *rit - 10 'A'; cout << temp; } else { cout << *rit; } } } void convert(const char *str, int n, int m) { if(*str == '\0') return; int x = 0; int y; while(*str != '\0') { x *= n; if((*str>='0') && (*str<='9')) { y = *str - '0'; } else if( (*str>='A') && (*str<='F') ) { y = 10 *str - 'A'; } else if( (*str>='a') && (*str<='f') ) { y = 10 *str - 'a'; } else { cout << "error input" << endl; return; } if( y>=n ) // n进制数字不能大于n { cout << "error input" << endl; return; } x = y; str ; } convert(x, n , m); } int main(void) { convert(1234, 10, 16); return 0; }
#include<iostream> void convert(char* num, int x, int y,char *num2) { __int64 n;int i,m; char a[16];char *p=a; n=(*num>='A'?*num-'A'+10:*num-'0');num++; while (*num) { n=n*x+(*num>='A'?*num-'A'+10:*num-'0'); num++; } for (m=0;n>y ;m++ ) { i=n%y; *p++=(i<10?'0'+i:'A'+i-10); n=n/y; } *p=(n<10?'0'+n:'A'+n-10); m=0; while (p>=a) { *num2++=*p--; } *num2='\0'; return ; } int main() { char s[16];convert("AB",16,10,s); printf("%s\n",s); return 0; }