Перевод из одной системы счисления в другую - C (СИ) (151074)
Формулировка задачи:
- #pragma hdrstop
- #pragma argsused
- #include <stdio.h>
- #include <malloc.h>
- #include <string.h>
- #ifdef _WIN32
- #include <tchar.h>
- #else
- typedef char _TCHAR;
- #define _tmain main
- #endif
- struct Line
- {
- char litter;
- struct Line *next;
- };
- const char dict[16][2]={
- {'0','0'},
- {'1','1'},
- {'2','10'},
- {'3','11'},
- {'4','100'},
- {'5','101'},
- {'6','110'},
- {'7','111'} ,
- {'8','1000'} ,
- {'9','1001'} ,
- {'A','1010'},
- {'B','1011'},
- {'C','1100'},
- {'D','1101'},
- {'E','1110'},
- {'F','1111'}};
- void enterString(struct Line *);
- struct Line * createElement(struct Line*);
- void outputString();
- char checkValue(char);
- void processingString(struct Line*);
- int getIndex(struct Line);
- int _tmain(int argc, _TCHAR* argv[])
- {
- struct Line string;
- struct Line *head = &string;
- puts("Enter string");
- enterString(&string);
- string=*head;
- processingString(&string);
- return 0;
- }
- void enterString(struct Line *string) {
- char chr;
- struct Line *head = string;
- while (scanf("%c",&chr) > 0) {
- if (chr=='!') {
- return;
- }
- if (checkValue(chr)!='\0') {
- string->litter=chr;
- }
- else continue;
- string=createElement(string);
- }
- }
- struct Line * createElement(struct Line *string)
- {
- string->next = malloc(sizeof(struct Line));
- string = string->next;
- string->next = NULL;
- return string;
- }
- char checkValue(char chr)
- {
- static char schr;
- if (strpbrk(&chr,"123456789ABCDEF \t")>0) {
- if (chr=='\t') {
- chr=' ';
- }
- if (chr==schr) {
- return '\0' ;
- }
- return schr=chr;
- }
- else return '\0';
- }
- int getIndex(struct Line string){
- return (int)string.litter>57?(int)string.litter-55:(int)string.litter-48;
- }
- void processingString(struct Line *string)
- {
- int i,uBOUND;
- char *pattern;
- struct Line *partString ;
- while (string->next!=NULL)
- {
- if (string->litter==' ') {
- string= string->next;
- continue;
- }
- partString=string->next;
- uBOUND=strlen(dict[getIndex(*string),1]);
- for (i = 0; i <= uBOUND; i++)
- {
- if (uBOUND>1) {
- string->litter=pattern[i-1];
- string=createElement(string);
- }
- else string->litter=pattern[i-1];
- }
- string->next=partString;
- string= string->next;
- }
- }
Решение задачи: «Перевод из одной системы счисления в другую»
- #include <stdio.h>
- #include <malloc.h>
- #include <string.h>
- struct Line
- {
- char litter;
- struct Line *next;
- };
- const char *dict[16][2]={
- {"0","0000"},
- {"1","0001"},
- {"2","0010"},
- {"3","0011"},
- {"4","0100"},
- {"5","0101"},
- {"6","0110"},
- {"7","0111"} ,
- {"8","1000"} ,
- {"9","1001"} ,
- {"A","1010"},
- {"B","1011"},
- {"C","1100"},
- {"D","1101"},
- {"E","1110"},
- {"F","1111"}};
- void enterString(struct Line *);
- struct Line * createElement(struct Line*);
- void processingString(struct Line*, struct Line*);
- void outputString(struct Line *);
- int value(char);
- int main(int argc, char* argv[])
- {
- struct Line Sstring, Dstring;
- puts("Enter string");
- enterString(&Sstring);
- outputString(&Sstring);
- processingString(&Sstring, &Dstring);
- outputString(&Dstring);
- return 0;
- }
- void outputString(struct Line *string) {
- if (string->litter) {
- putchar(string->litter);
- outputString(string->next);
- }
- else
- putchar('\n');
- }
- void enterString(struct Line *string) {
- char chr;
- struct Line *item = string;
- while ((chr=toupper(getchar())) != '!') {
- if (( chr>='0' && chr<='9' )||
- ( chr>='A' && chr<='F' ) )
- {
- item->litter = chr;
- item = createElement(item);
- }
- }
- item->litter='\0';
- }
- struct Line * createElement(struct Line *string)
- {
- string->next = malloc(sizeof(struct Line));
- string = string->next;
- string->next = NULL;
- return string;
- }
- void processingString(struct Line *source, struct Line *destination)
- {
- struct Line *ditem = destination, *sitem = source;
- while (sitem->litter) {
- int v = value(sitem->litter);
- ditem->litter = dict[v][1][0];
- (ditem = createElement(ditem))->litter = dict[v][1][1];
- (ditem = createElement(ditem))->litter = dict[v][1][2];
- (ditem = createElement(ditem))->litter = dict[v][1][3];
- (ditem = createElement(ditem))->litter = ' ';
- (ditem = createElement(ditem))->litter = '\0';
- sitem = sitem->next;
- }
- }
- int value(char chr) {
- if (chr>='0' && chr<='9')
- return chr - '0';
- else
- return chr - 'A' + 10;
- }
Объяснение кода листинга программы
В этом коде реализована функция перевода строки из одной системы счисления в другую. Структура данных, представляющая строку, состоит из символа и указателя на следующий элемент. Для работы со строкой вводится функция создания нового элемента списка, а также функция вывода строки на экран. В функции ввода строки пользователю предлагается ввести строку в кодировке ASCII. Затем эта строка преобразуется в список элементов, где каждый символ представлен отдельным элементом списка. Функция обработки строки принимает два указателя на начало и конец строки. В этой функции происходит перевод каждого символа строки из одной системы счисления в другую, при этом каждому числу в двоичной системе счисления соответствует определенный набор символов в шестнадцатеричной системе счисления. Функция определения значения символа в строке вычисляет числовое значение символа в соответствии с его позицией в алфавите. В функции вывода строки на экран происходит обход всех элементов списка и вывод их на экран. При этом если элемент является последним в списке, то после него выводится символ новой строки.
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д