
03.08.2009, 22:01
|
|
Новичок
Регистрация: 07.06.2009
Сообщений: 9
Провел на форуме: 28710
Репутация:
5
|
|
перевод из десятичной системы счисления в любую (до 34)
Код:
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#define PROCESSOR_BIT 32
char* dec2x(int number, int basis)
{
char *result = (char*)malloc((PROCESSOR_BIT + 1) * sizeof(char));
memset(result, '0', PROCESSOR_BIT * sizeof(char));
result[PROCESSOR_BIT] = '\0'; // each string must end with '\0'
const char *signs = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int div = 0;
int buf = 0;
if (basis > strlen(signs) || basis < 2) {
printf("Sorry, it is impossible, good bye!\n");
free(result);
exit(1);
}
while (number) {
div = number % basis;
number /= basis;
result[buf] = signs[div];
buf++;
}
int i, j;
for (i = 0; i < PROCESSOR_BIT - i; i++) {
buf = result[i];
result[i] = result[PROCESSOR_BIT - i - 1];
result[PROCESSOR_BIT - i - 1] = buf;
}
//удаляем незначащие нули
buf = 0;
while (result[buf] == '0') buf++;
char *newresult = (char *)malloc(PROCESSOR_BIT - buf + 1);
for (i = buf, j = 0; j < PROCESSOR_BIT - buf; i++, j++)
newresult[j] = result[i];
newresult[j] = '\0';
free(result);
return newresult;
}
int main()
{
int i, j;
puts("Enter a number: ");
scanf("%d", &i);
puts("Enter new basis: ");
scanf("%d", &j);
printf("Your number in %d basis is %s\n", j, dec2x(i, j));
getchar();
return 0;
}
Последний раз редактировалось alex912; 03.08.2009 в 22:49..
|
|
|