|
|
发表于 2006-9-17 21:45:52
|
显示全部楼层
语言要边学边练的,不要操之过急。
字母表是随便规定的,你当然可以用小写字母代替之。但次序不能乱
你不明白的是如何在C里头实现进制转换吧?
比如 16进制 "0x1FFC" ----> 10进制 "8188"
首先你键盘输入的 "0x1FFC" 和 屏幕输出的"8188" 都是 字符串。也就是怎么实现这个字符串之间的转换? 我想你问的是这个吧
流程是: "0x1FFC" ---> 用strtol 保存为一个整数n ----> 调用 bin2str ---> 输出字符串"8188"
可以实现任意进制的转化
- /* 任意数值转化演示, 仅适合正数 */
- #include <stdio.h>
- #include <string.h>
- /* buffer size for storing result string */
- int const MAX_LEN=64;
- /* result string alphabet, base 2~36 is compatible */
- char const alphabet[]="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
- char * bin2str(char *p, int n, int base)
- {
- while(n){
- p--;
- *p=alphabet[n%base];
- n/=base;
- }
- return p;
- }
- int main()
- {
- char result_str[MAX_LEN+1];
- result_str[MAX_LEN]=0;
- char input_str[MAX_LEN+1];
- int n;
- int in_base, out_base;
- printf("input string: ");
- fgets(input_str, MAX_LEN, stdin);
- input_str[strlen(input_str)-1]='\0';
- printf("input base(2~32): ");
- scanf("%d",&in_base);
- printf("output base(2~32): ");
- scanf("%d",&out_base);
- n=strtol(input_str, NULL, in_base);
- char *p=bin2str(result_str, n, out_base);
- printf("%s (base %d) ---> %s (base %d) \n", input_str,in_base, p, out_base);
- }
复制代码~/coding/c $ ./a.out
input string: 0x1ffc
input base(2~32): 16
output base(2~32): 10
0x1ffc (base 16) ---> 8188 (base 10) |
|