10进制转换为2~16进制
程序员文章站
2024-03-18 19:12:28
...
10进制数n转换为 base(2~16)进制的转换法则:除以base倒取余。
简单原理:n=(n/base) * base + n%base (此处的除法为整除)
如何倒着取余?使用栈的先进后出特性的来完成。
/*
* @Author: jinbo.ma
* @Mail: [email protected]
* @Date: 2021-04-30 16:07:07
* @LastEditTime: 2021-04-30 17:36:55
*/
#include <stdio.h>
#include <stdlib.h>
#define MAX 1024
#define MIN 0
#define BASE_STACK_SIZE 20
/**
* is legal input
* 1 => true
* 0 => false
**/
short is_legal_input(int base, int n) {
if ( 2 > base || base > 16 ) {
return 0;
}
if ( MIN > n || n > MAX ) {
return 0;
}
return 1;
}
char * exchange(int base, int n) {
short base_stack[BASE_STACK_SIZE], top = 0, index = 0;
char base_storage[16] = {'0','1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
char *res = (char*)calloc(sizeof(char), BASE_STACK_SIZE);
while (n) {
base_stack[top++] = n % base;
n /= base;
printf("stack[%d]=%d n=%d\n", top-1, base_stack[top-1], n);
}
while (top) {
res[index++] = base_storage[base_stack[--top]];
}
return res;
}
int main() {
int base = 0, n = 0;
printf("\nInput exchange base and number:");
scanf("%d %d", &base, &n);
if ( 0 == is_legal_input(base, n) ) {
printf("Input isn't legal.\n");
return 1;
}
char * p = exchange(base, n);
printf("base=%d n=%d exchange=%s\n", base, n, p);
return 0;
}
运行结果
# 十进制转二进制
Input exchange base and number:2 10
stack[0]=0 n=5
stack[1]=1 n=2
stack[2]=0 n=1
stack[3]=1 n=0
base=2 n=10 exchange=1010
# 十进制转八进制
Input exchange base and number:8 159
stack[0]=7 n=19
stack[1]=3 n=2
stack[2]=2 n=0
base=8 n=159 exchange=237
# 十进制转16进制
Input exchange base and number:16 255
stack[0]=15 n=15
stack[1]=15 n=0
base=16 n=255 exchange=FF
Input exchange base and number:16 1024
stack[0]=0 n=64
stack[1]=0 n=4
stack[2]=4 n=0
base=16 n=1024 exchange=400
# 十进制转换为七进制
Input exchange base and number:7 8
stack[0]=1 n=1
stack[1]=1 n=0
base=7 n=8 exchange=11
# 错误输入
Input exchange base and number:17 10
Input isn't legal.