Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Задание 3-1
- // Пользователь вводит в консоли шестнадцатеричное число. Напишите программу, которая
- // преобразует строку в число. Перевод строки в число необходимо оформить в виде
- // функции. Допустимые символы: 0-9, a-f, A-F. Пользоваться решениями на основе
- // стандартной библиотеки не разрешается.
- #include <stdio.h>
- #define str_maxlen 100
- void str_read(char s[], char end) {
- int i = 0;
- while ((s[i] = getchar()) != end && s[i] != EOF)
- i++;
- s[i] = '\0';
- }
- //////////////////////////////////////////////////
- int hexNumber(char c) {
- if (c >= '0' && c <= '9') return c - '0';
- if (c >= 'a' && c <= 'f') return c - 'a' + 10;
- if (c >= 'A' && c <= 'F') return c - 'f' + 10;
- return -1;
- }
- int str_parse_hex(char s[]) {
- int n = 0, d, i=0;
- while ((d = hexNumber(s[i])) != -1) {
- n = 16 * n + d;
- i++;
- }
- return n;
- }
- int main() {
- printf("0x");
- char s[str_maxlen];
- str_read(s, '\n'); // reads to newline! no EOF required!
- int n = str_parse_hex(s);
- printf("0x%s is %d\n", s, n);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement