主题:[原创]小于36的任意进制间的相互转换简单实现
这个函数是非常不严谨的 把a进制转换成b进制函数。原型中的a,b分别表示a,b进制,sa是要转换的a进制字符,sb表示的是(如果转换成功)得到的b进制数。
[code=c]int ( a_to_b )( char *sb,const char *sa, unsigned short a,unsigned short b ) {
const unsigned char table1[ 128 ] = {
36,36,36,36,36,36,36,36,36,36,36,36,36,36,36,36,
36,36,36,36,36,36,36,36,36,36,36,36,36,36,36,36,
36,36,36,36,36,36,36,36,36,36,36,36,36,36,36,36,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,36,36,36,36,36,36,
36,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,
25,26,27,28,29,30,31,32,33,34,35,36,36,36,36,36,
36,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,
25,26,27,28,29,30,31,32,33,34,35,36,36,36,36,36
};
const char table2[ ] =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" ;
unsigned long total = 0 ;
unsigned char ch = 0 ;
char noname_p[31]={0},*p = noname_p ;
if ( !sb || !sa || 2>a || 2>b || 36<a || 36<b ) return 0 ;
for ( --sa;*++sa ==' '; ) ;//跳过空格
if ( *sa=='+' || *sa=='-' )
*p = *sa++ ;//符号
if ( (sa[ 0 ] == '0') && (sa[1]=='x' || sa[1]=='X') )
{ //0x或0X 前导的是16进制格式
a = 16 ;
sa += 2 ;
}
for ( --sa;*++sa =='0'; ) ;//跳过0
for ( total=0,--sa; (ch=table1[*++sa])<a; total = total*a + ch )
;//把a进制字符转换成数
if ( *sa )
{ //sa中有字符不是a进制字符
*sb = '\0' ;
return 0 ;
}
if ( *p )
{ //复制符号
*sb++ = *p;
*p =0 ;
}
do { //把total转换成b进制字符(反序)
*++p = table2[ total%b ] ;
} while( (total /= b)>0 );
*++p = 0 ;--sb;
while( *++sb = *--p ) ;//把b进制字符复制到sb中
return 1 ;//转换成功
}[/code]
[code=c]int ( a_to_b )( char *sb,const char *sa, unsigned short a,unsigned short b ) {
const unsigned char table1[ 128 ] = {
36,36,36,36,36,36,36,36,36,36,36,36,36,36,36,36,
36,36,36,36,36,36,36,36,36,36,36,36,36,36,36,36,
36,36,36,36,36,36,36,36,36,36,36,36,36,36,36,36,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,36,36,36,36,36,36,
36,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,
25,26,27,28,29,30,31,32,33,34,35,36,36,36,36,36,
36,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,
25,26,27,28,29,30,31,32,33,34,35,36,36,36,36,36
};
const char table2[ ] =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" ;
unsigned long total = 0 ;
unsigned char ch = 0 ;
char noname_p[31]={0},*p = noname_p ;
if ( !sb || !sa || 2>a || 2>b || 36<a || 36<b ) return 0 ;
for ( --sa;*++sa ==' '; ) ;//跳过空格
if ( *sa=='+' || *sa=='-' )
*p = *sa++ ;//符号
if ( (sa[ 0 ] == '0') && (sa[1]=='x' || sa[1]=='X') )
{ //0x或0X 前导的是16进制格式
a = 16 ;
sa += 2 ;
}
for ( --sa;*++sa =='0'; ) ;//跳过0
for ( total=0,--sa; (ch=table1[*++sa])<a; total = total*a + ch )
;//把a进制字符转换成数
if ( *sa )
{ //sa中有字符不是a进制字符
*sb = '\0' ;
return 0 ;
}
if ( *p )
{ //复制符号
*sb++ = *p;
*p =0 ;
}
do { //把total转换成b进制字符(反序)
*++p = table2[ total%b ] ;
} while( (total /= b)>0 );
*++p = 0 ;--sb;
while( *++sb = *--p ) ;//把b进制字符复制到sb中
return 1 ;//转换成功
}[/code]