将数字转换为基数的代码部分

huangapple go评论50阅读模式
英文:

Working on a piece of code to convert numbers into base

问题

我是一名新手,正在尽力学习,请理解。

我正在为一门课程的作业做准备:

○ 向用户询问一个数字作为字符串(在程序中设置最大位数是可以的);

○ 您的程序应该询问基数(一个介于2到16之间的整数);

○ 有了这些信息,您的程序应该计算该数字的二进制和十进制表示,然后将其作为字符串打印出来;

○ 例如,如果用户输入:FA 和 16,您的程序应该打印出:

-- "FA在16进制中是:10进制中的250和2进制中的11111010"

○ 如果用户输入:34 和 5,您的程序应该打印:

-- "34在5进制中是:10进制中的19和2进制中的10011"

到目前为止,通过与导师和朋友的合作,我得到了以下代码:

n = str(input("输入一个介于2和16之间的数字:"))

while(True):
  in_num = int(input("是什么基数?:"))
  if in_num < 2 or in_num > 16:
    print("请输入介于2和16之间的有效数字")
  else:
    dec = int(n, in_num)
    print(n, "在基数", in_num, "中是:", dec, "在10进制中和", bin(dec), "在2进制中")

我相信根据我与导师的交流,我还需要包括三进制、四进制等的代码。

如果有任何帮助,我将不胜感激。

我尝试在Replit上运行这个代码,但出现了一个语法错误,我无法检测到。

英文:

First, I'm a newbie and trying my best, so be understanding.

I am working on an assignment for a class:

○ Asks the user a number as a string (to set a maximum number of digits in your program is ok);

○ Your program should ask which is the base (an Integer from 2 to 16);

○ With that information, your program should compute the binary and decimal representations of the number, then print it out as a string

○ For example, if the user enters: FA and 16, your program should print out:

-- "FA in base 16 is: 250 in base 10 and 11111010 in base 2"

○ If the user enters: 34 and 5, your program should print:

-- "34 in base 5 is: 19 in base 10 and 10011 in base 2"

What I have so far by working with both a tutor and a friend is this:

n = str(input (&quot;Enter A Number between 2 and 16&quot;))

while(True):
  in_num = str(input(&quot;What is the base?:&quot; ))
  if in_num not in range(2,16):
    print(“enter a valid number between 2 and 16”)
  else:
print(bin(dec), &quot;in binary.&quot;)
print(oct(dec), &quot;in octal.&quot;)
print(hex(dec), &quot;in hexadecimal.&quot;)

    
“”.join(f”{ord(i):08b}” for i in str
Float()

   print (n, &quot;in base&quot;, in_num, is&quot;&quot; )  ]]

I believe from my conversations with my tutor that I have to also include lines of code for ternary, quaternary, etc.

Any help would be appreciated.

I have tried running this on Replit but it has a syntax error that I'm unable to detect.

答案1

得分: 0

def convert_to_decimal(number, base):
    decimal = 0
    power = len(number) - 1
    for digit in number:
        if digit.isdigit():
            value = int(digit)
        else:
            value = ord(digit.upper()) - ord('A') + 10
        decimal += value * (base ** power)
        power -= 1
    return decimal

n = input("Enter a number between 0 and 9 or A and F: ")
base = int(input("Enter the base (between 2 and 16): "))

decimal_representation = convert_to_decimal(n, base)
binary_representation = bin(decimal_representation)[2:]

print(f"{n} in base {base} is: {decimal_representation} in base 10 and {binary_representation} in base 2.")
英文:
def convert_to_decimal(number, base):
    decimal = 0
    power = len(number) - 1
    for digit in number:
        if digit.isdigit():
            value = int(digit)
        else:
            value = ord(digit.upper()) - ord(&#39;A&#39;) + 10
        decimal += value * (base ** power)
        power -= 1
    return decimal

n = input(&quot;Enter a number between 0 and 9 or A and F: &quot;)
base = int(input(&quot;Enter the base (between 2 and 16): &quot;))

decimal_representation = convert_to_decimal(n, base)
binary_representation = bin(decimal_representation)[2:]

print(f&quot;{n} in base {base} is: {decimal_representation} in base 10 and {binary_representation} in base 2.&quot;)

答案2

得分: 0

只使用int(s, base)在所有实际用途中。它支持基数高达36,因此int('python', 36)等于1570137287。

现在要将字符串表示从基数转换为十进制,首先我们需要一个字母表。我们需要一个数字列表,以便我们可以为基数下面的每个数值提供一个数字,并查找字母表以了解与数字关联的值。十六进制使用数字0123456789加上abcdef,基本拉丁字母表中有26个字母,如果我们使用所有字母,我们可以将数字转换为基数36。

from string import ascii_lowercase, digits

ALPHABET = digits + ascii_lowercase

上述代码创建字符串'0123456789abcdefghijklmnopqrstuvwxyz'并将其赋给ALPHABET。我们可以使用ALPHABET.index(c)将数字表示转换回数值。

然后观察数字123456789,它等于1 * 10^8 + 2 * 10^7 + 3 * 10^6 + 4 * 10^5 + 5 * 10^4 + 6 * 10^3 + 7 * 10^2 + 8 * 10^1 + 9 * 10^0,从左到右,位值的幂递减。最左边的位置具有最大的幂,它等于字符串长度减1,每个后续位置的幂都减少1,直到最后一个位置的幂为0。

同样的数字在二进制中是'111010110111100110100010101'。

这意味着:

1 * 2^26 +
1 * 2^25 +
1 * 2^24 +
0 * 2^23 +
1 * 2^22 +
0 * 2^21 +
1 * 2^20 +
1 * 2^19 +
0 * 2^18 +
1 * 2^17 +
1 * 2^16 +
1 * 2^15 +
1 * 2^14 +
0 * 2^13 +
0 * 2^12 +
1 * 2^11 +
1 * 2^10 +
0 * 2^9 +
1 * 2^8 +
0 * 2^7 +
0 * 2^6 +
0 * 2^5 +
1 * 2^4 +
0 * 2^3 +
1 * 2^2 +
0 * 2^1 +
1 * 2^0。

去掉位值为0的位置:

1 * 2^26 +
1 * 2^25 +
1 * 2^24 +
1 * 2^22 +
1 * 2^20 +
1 * 2^19 +
1 * 2^17 +
1 * 2^16 +
1 * 2^15 +
1 * 2^14 +
1 * 2^11 +
1 * 2^10 +
1 * 2^8 +
1 * 2^4 +
1 * 2^2 +
1 * 2^0。

这些数字值为:

67108864 +
33554432 +
16777216 +
4194304 +
1048576 +
524288 +
131072 +
65536 +
32768 +
16384 +
2048 +
1024 +
256 +
16 +
4 +
1。

十六进制中的数字123456789要紧凑得多:

75bcd15:

7 * 16^6 +
5 * 16^5 +
b * 16^4 +
c * 16^3 +
d * 16^2 +
1 * 16^1 +
5 * 16^0。

各项为:

7 * 16777216 +
5 * 1048576 +
b * 65536 +
c * 4096 +
d * 256 +
1 * 16 +
5 * 1。

(b的数值为11,c = 12,d = 13)

因此,要将数字从任何基数转换为十进制(我必须补充这是错误的术语,数字没有任何数字,数字有数字,您是在解释数字以获取数字值),反转字符串表示的顺序,从左到右,为第一个元素分配索引0,第二个为1,依此类推,对于每个元素,查询ALPHABET以获取数字的值,将该值乘以基数的索引幂,然后求和,完成。

示例实现:

from string import ascii_lowercase, digits

ALPHABET = digits + ascii_lowercase

def interpret_numeral(numeral, base):
    return sum(ALPHABET.index(digit) * base ** index for index, digit in enumerate(numeral[::-1]))

示例用法:

interpret_numeral('111010110111100110100010101', 2)
# 123456789

interpret_numeral('726746425', 8)
# 123456789

interpret_numeral('123456789', 10)
# 123456789

interpret_numeral('75bcd15', 16)
# 123456789

如果要获取基数为36的'21i3v9'的数值,例如,使用interpret_numeral('21i3v9', 36),如果没有输出,请尝试使用print(interpret_numeral('21i3v9', 36)),它应该返回'123456789'。

要将数字转换为基数(以表示基数中的数值),我们可以重复将数字除以基数,将整数部分赋给数字并获取余数,直到数字为0。

这将以相反的顺序获取数字,然后我们需要反转字符串。

解释123456789的十进制操作:

123456789 = 12345678 * 10 + 9
12345678 = 1234567 * 10 + 8
1234567 = 123456 * 10 + 7
123456 = 12345 * 10 + 6
12345 = 1234 * 10 + 5
1234 = 123 * 10 + 4
123 = 12 * 10 + 3
12 = 1 * 10 + 2
1 = 0 * 10 + 1

十六进制:

123456789 = 7716049 * 16 + 5
7716049 = 482253 * 16 + 1
482253 = 30140 * 16 + 13
30140 = 1883 * 16 + 12
1883 = 117 * 

<details>
<summary>英文:</summary>

Just use `int(s, base)` for all practical purposes. It supports bases up to 36, so `int(&#39;python&#39;, 36)` is 1570137287.

Now to convert the string representation from base to decimal, first we need an alphabet. We need a list of digits so that we can give a digit for each numerical value below the base and look up the alphabet to know the value associated with the digit. Hexadecimal uses digits 0123456789 plus abcdef, there are 26 letters in the basic Latin alphabet, if we use all letters we can convert numbers up to base 36.


from string import ascii_lowercase, digits

ALPHABET = digits + ascii_lowercase


The above creates the string `&#39;0123456789abcdefghijklmnopqrstuvwxyz&#39;` and assigns it to `ALPHABET`. We can use `ALPHABET.index(c)` to convert the digit representation back to numerical value.


Then observe the number 123456789, it is equal to 1 * 10&lt;sup&gt;8&lt;/sup&gt; + 2 * 10&lt;sup&gt;7&lt;/sup&gt; + 3 * 10&lt;sup&gt;6&lt;/sup&gt; + 4 * 10&lt;sup&gt;5&lt;/sup&gt; + 5 * 10&lt;sup&gt;4&lt;/sup&gt; + 6 * 10&lt;sup&gt;3&lt;/sup&gt; + 7 * 10&lt;sup&gt;2&lt;/sup&gt; + 8 * 10&lt;sup&gt;1&lt;/sup&gt; + 9 * 10&lt;sup&gt;0&lt;/sup&gt;, from left to right, the power of the place value decreases. The leftmost place has the most power, it is equal to the length of the string minus one, and each subsequent place has one less power, until the last place has power 0.

The same number in binary is `111010110111100110100010101`.

It means:


1 * 2&lt;sup&gt;26&lt;/sup&gt; +
1 * 2&lt;sup&gt;25&lt;/sup&gt; +
1 * 2&lt;sup&gt;24&lt;/sup&gt; +
0 * 2&lt;sup&gt;23&lt;/sup&gt; +
1 * 2&lt;sup&gt;22&lt;/sup&gt; +
0 * 2&lt;sup&gt;21&lt;/sup&gt; +
1 * 2&lt;sup&gt;20&lt;/sup&gt; +
1 * 2&lt;sup&gt;19&lt;/sup&gt; +
0 * 2&lt;sup&gt;18&lt;/sup&gt; +
1 * 2&lt;sup&gt;17&lt;/sup&gt; +
1 * 2&lt;sup&gt;16&lt;/sup&gt; +
1 * 2&lt;sup&gt;15&lt;/sup&gt; +
1 * 2&lt;sup&gt;14&lt;/sup&gt; +
0 * 2&lt;sup&gt;13&lt;/sup&gt; +
0 * 2&lt;sup&gt;12&lt;/sup&gt; +
1 * 2&lt;sup&gt;11&lt;/sup&gt; +
1 * 2&lt;sup&gt;10&lt;/sup&gt; +
0 * 2&lt;sup&gt;9&lt;/sup&gt; +
1 * 2&lt;sup&gt;8&lt;/sup&gt; +
0 * 2&lt;sup&gt;7&lt;/sup&gt; +
0 * 2&lt;sup&gt;6&lt;/sup&gt; +
0 * 2&lt;sup&gt;5&lt;/sup&gt; +
1 * 2&lt;sup&gt;4&lt;/sup&gt; +
0 * 2&lt;sup&gt;3&lt;/sup&gt; +
1 * 2&lt;sup&gt;2&lt;/sup&gt; +
0 * 2&lt;sup&gt;1&lt;/sup&gt; +
1 * 2&lt;sup&gt;0&lt;/sup&gt;

Get rid of where the places have no value:

1 * 2&lt;sup&gt;26&lt;/sup&gt; +
1 * 2&lt;sup&gt;25&lt;/sup&gt; +
1 * 2&lt;sup&gt;24&lt;/sup&gt; +
1 * 2&lt;sup&gt;22&lt;/sup&gt; +
1 * 2&lt;sup&gt;20&lt;/sup&gt; +
1 * 2&lt;sup&gt;19&lt;/sup&gt; +
1 * 2&lt;sup&gt;17&lt;/sup&gt; +
1 * 2&lt;sup&gt;16&lt;/sup&gt; +
1 * 2&lt;sup&gt;15&lt;/sup&gt; +
1 * 2&lt;sup&gt;14&lt;/sup&gt; +
1 * 2&lt;sup&gt;11&lt;/sup&gt; +
1 * 2&lt;sup&gt;10&lt;/sup&gt; +
1 * 2&lt;sup&gt;8&lt;/sup&gt; +
1 * 2&lt;sup&gt;4&lt;/sup&gt; +
1 * 2&lt;sup&gt;2&lt;/sup&gt; +
1 * 2&lt;sup&gt;0&lt;/sup&gt;

The numerical values are:

67108864 +
33554432 +
16777216 +
4194304 +
1048576 +
524288 +
131072 +
65536 +
32768 +
16384 +
2048 +
1024 +
256 +
16 +
4 +
1

The number 123456789 in hexadecimal is much more compact:

75bcd15:

7 * 16&lt;sup&gt;6&lt;/sup&gt; +
5 * 16&lt;sup&gt;5&lt;/sup&gt; +
b * 16&lt;sup&gt;4&lt;/sup&gt; +
c * 16&lt;sup&gt;3&lt;/sup&gt; +
d * 16&lt;sup&gt;2&lt;/sup&gt; +
1 * 16&lt;sup&gt;1&lt;/sup&gt; +
5 * 16&lt;sup&gt;0&lt;/sup&gt;

The terms are:

7 * 16777216 +
5 * 1048576 +
b * 65536 +
c * 4096 +
d * 256 +
1 * 16 +
5 * 1

(b has a numeric value of 11, c = 12 and d = 13)

So to convert a number from any base to decimal (I have to add this is wrong terminology, numbers don&#39;t have any digits, numerals have, you are interpreting numeral to get numeric value), reverse the order of the string representation, go from left to right, assign indexes to the first element 0 and the second 1 et cetera, for each element, query `ALPHABET` to get value of digit, multiply the value by the base raised to the index, and then sum, done.

Example implementation:

from string import ascii_lowercase, digits

ALPHABET = digits + ascii_lowercase

def interpret_numeral(numeral, base):
return sum(ALPHABET.index(digit) * base ** index for index, digit in enumerate(numeral[::-1]))


Example usage:

interpret_numeral('111010110111100110100010101', 2)
#123456789

interpret_numeral('726746425', 8)
#123456789

interpret_numeral('123456789', 10)
#123456789

interpret_numeral('75bcd15', 16)
#123456789


If you want to get the numerical value of `&#39;21i3v9&#39;` in base 36 for example, use `interpret_numeral(&#39;21i3v9&#39;, 36)`, if you don&#39;t get any output, try using `print(interpret_numeral(&#39;21i3v9&#39;, 36))`, it should return `123456789`.

To convert a number to a base (to represent the numeric value in a base), we can repeatedly divide the number by base, assign the whole part to the number and get the remainder, until the number is 0.

This will get the digits in reverse order, we then need to reverse the string.

Operation for interpreting 123456789 in decimal:

123456789 = 12345678 * 10 + 9
12345678 = 1234567 * 10 + 8
1234567 = 123456 * 10 + 7
123456 = 12345 * 10 + 6
12345 = 1234 * 10 + 5
1234 = 123 * 10 + 4
123 = 12 * 10 + 3
12 = 1 * 10 + 2
1 = 0 * 10 + 1


Hexadecimal:

123456789 = 7716049 * 16 + 5
7716049 = 482253 * 16 + 1
482253 = 30140 * 16 + 13
30140 = 1883 * 16 + 12
1883 = 117 * 16 + 11
117 = 7 * 16 + 5
7 = 0 * 16 + 7


We have the numeric digits at this point. All we need to do is then lookup `ALPHABET` to convert to associated string:

def base_represent(number, base):
string = ''
while number:
number, digit = divmod(number, base)
string = ALPHABET[digit] + string
return string


Example usage:

for base in range(2, 37):
print(base_represent(123456789, base))


Output:

111010110111100110100010101
22121022020212200
13112330310111
223101104124
20130035113
3026236221
726746425
277266780
123456789
63762a05
35418a99
1c767471
12579781
ac89bc9
75bcd15
51g2a21
3b60f89
2bg64ae
1ibc1j9
194gh7f
11l0805
j43jfb
fc2egl
cg15le
aa44a1
8g86ni
74nqb1
60fshj
52ce69
49l302
3lnj8l
353c3r
2od2i1
2c9g1t
21i3v9

    

</details>



huangapple
  • 本文由 发表于 2023年7月20日 10:00:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76726208.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定