本文介绍了在数字基之间转换数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个在数字基数之间转换的程序.例如,八进制为8,十进制为10.可以将字母AZ视为基数26.

I'm working on a program that converts between number bases. For example Octal is 8, decimal is 10. Letters A to Z could be considered as base 26.

我想将"A"转换为0,将Z转换为25,将"AA"转换为27,将"BA"转换为53.

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

在我开始编码之前,我正在纸上做这个,所以我理解了这个过程.首先,我尝试将533转换为26.

Before I start coding I'm doing it on paper so I understand the process. To start out I'm trying to convert 533 to base 26.

哪种算法最适合这样做?

What algorithm is best for doing this?

推荐答案

您需要为每个字母分配一个数字",例如:

You need to assign a "digit" to each letter, like:

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

然后,您的{20,13}变为UN.

转换为UN -> {20,13} -> (20 * 26 + 13) -> 52.

通过进一步的示例,让我们尝试10163,它是随机抽取的.

By way of further example, let's try the number 10163, just plucked out of the air at random.

将其除以26,直到得到小于26的数字(即两次),然后得到 15 ,其分数为0.03402366.

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

将其乘以26,您将得到 0 ,分数为0.88461516.

Multiply that by 26 and you get 0 with a fractional part of 0.88461516.

那个乘以26,您会得到 23 (实际上在我的计算器上为22.99999416,但是由于初始除法只有两步,所以我们在这里停止-略有误差是由于对浮点数进行了四舍五入).

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

因此,数字"是{15,0,23},这是数字" PAX.哇,真是巧合?

So the "digits" are {15,0,23} which is the "number" PAX. Wow, what a coincidence?

要将PAX转换回十进制,其

  P * 26 + A * 26 + X * 26

 P * 26 + A * 26 + X * 26

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

这篇关于在数字基之间转换数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:50