📜 ⬆️ ⬇️

Conversion hex-> dec - we are looking for beautiful solutions

After discussing the algorithms for finding numbers in the line , the idea arose to consider some other tasks in the same vein. The task of converting an integer from a hexadecimal system into a decimal system seemed appropriate: not very cumbersome, with at least one obvious algorithm and, perhaps, many not obvious, and understandable.



Given a string containing a nonnegative integer in a hexadecimal system. The number is written in numbers 0..9A..F (letters - only big), it is guaranteed that there are no non-digit characters in the string. It is required to receive the line containing decimal record of such number. The length of the input string does not exceed 100,000 bytes.
')
Write solutions in any languages ​​- the most beautiful, the shortest, the most effective ... For solutions on a Turing machine, I suggest using only the characters "space, 0, 1" (do not enter new ones), and write the input and output numbers in quadruple bits (separated by spaces or not - at your discretion). On Brainfuck, the input string must be entered, and the output string must be printed.

UPD. Using built-in or library BigNum, of course, is good, but somehow not very interesting. Let's do without it!

For the seed, the solution is in C # (which cannot be called either beautiful, short or effective):

         static unsafe string Hex2Dec (string x) {
             int l = x.Length;
             int ll = l + l / 4 + 3;
             sbyte [] m = new sbyte [ll];
             int i = l;
             foreach (char c in x) m [- i] = (sbyte) (c <'A'? c-'0 ': c-' A '+ 10);
             int lk = ll;
             while (l> 0) {
                 int k = 0, l1 = 0;
                 while (l> 0) {
                     k = (k << 4) + m [- l];
                     m [l] = (sbyte) (k / 10);
                     if (l1 == 0 && k> = 10) l1 = l + 1;
                     k% = 10;
                 }
                 m [- lk] = (sbyte) (k + 48);
                 l = l1;
             }
             string res;
             fixed (sbyte * c = m) {res = new string (c, lk, ll-lk);  }
             return res;
         }

Source: https://habr.com/ru/post/113688/


All Articles