Converting numbers between databases

I am working on a program that converts number bases. For example, Octal is 8, decimal is 10. The letters A to Z can be thought of as base 26.

I want to convert a number like "A" to 0, Z to 25, "AA" to 27, and "BA" to 53.

Before I start coding, I do it on paper to understand the process. For starters, I'm trying to convert 533 to base 26.

Which algorithm is best for this?

+4
source share
4 answers

You need to assign a "number" for each letter, for example:

 A = 0 N = 13 B = 1 O = 14 C = 2 P = 15 D = 3 Q = 16 E = 4 R = 17 F = 5 S = 18 G = 6 T = 19 H = 7 U = 20 I = 8 V = 21 J = 9 W = 22 K = 10 X = 23 L = 11 Y = 24 M = 12 Z = 25 

Then your {20,13} will become UN .

Convert back UN -> {20,13} -> (20 * 26 + 13) -> 52 .

As a further example, try number 10163, just torn out of thin air at random.

Divide this by 26 until you get a number less than 26 (i.e. twice), and get 15 with a fraction of 0.03402366.

Multiply this by 26 and you will get 0 with a fraction of 0.88461516.

Multiply this by 26, and you get 23 (actually 22.99999416 on my calculator, but since the initial division was just two steps, we stop here - very little inaccuracy is due to the fact that floating-point numbers are rounded).

Hence, the "numbers" {15,0,23} , which are the "number" of PAX . Wow, what a coincidence?

To convert PAX back to decimal, its

P * 26 2 + A * 26 1 + X * 26 0

or

  (15 * 676) + (0 * 26) + 23 = 10140 + 0 + 23 = 10163 
+3
source

Let's take a step back a second and look at the decimal.

What does the number "147" mean? Rather, what do the symbols "1", "4" and "7" mean when they are located so that?

There are ten digits in decimal, and after that we add another digit to the left of the first and so on as our number increases. Therefore, after "9" = 9 * 1 we get "10" = 1 * 10 + 0 * 1. So, "147" is 1 * 10 ^ 2 + 4 * 10 + 7 * 1 = 147. Similarly, we can go back - 147/10 ^ 2 = 1, which corresponds to the symbol '1'. (147% 10 ^ 2) / 10 = 4, which corresponds to the symbol "4". And 147% 10 = 7, which corresponds to the symbol "7".

This works for any base N - if we get the number 0, which displays the first character in our set. The number 1 is matched with the second character, and so on, until the number N-1 maps to the last character in our set of digits.

+2
source

You convert 20 and 13 into characters that represent 20 and 13 in base notation 26. It looks like you are using the letters of the alphabet so that it will be UN (where A is 0 and Z is 25).

0
source

What language do you write it in? If you do this in Perl, you can use the CPAN Math :: Fleximal module, which I wrote many years ago while I was bored. If you use a language with infinite integers, life becomes much easier. All you have to do is take the characters, convert them to an array of integers, then do a calculation to turn that into a number.

0
source

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


All Articles