임의의 베이스에서 정수를 문자열로 변환하려면 어떻게 해야 합니까?
Python을 통해 특정 베이스의 문자열에서 쉽게 정수를 생성할 수 있습니다.
int(str, base).
역순서: 정수에서 문자열 생성을 수행합니다.기능하고 싶다int2base(num, base)
를 들면 다음과 같은 것입니다
int(int2base(x, b), b) == x
함수 이름/인수 순서가 중요하지 않습니다.
의 번호에 대해서x
베이스 " " "b
그그int()
받아들이겠습니다.
이것은 쓰기 쉬운 함수입니다.사실 이 질문에서 설명하는 것보다 쉽습니다.하지만 뭔가 놓치고 있는 것 같아요.
는 그 있습니다.bin
,oct
,hex
, 몇 할 수
(2.2)와의 호환성이 필요한 이전 버전의 Python에서는 이러한 기능을 사용할 수 없습니다.
다른 베이스에 대해서도 같은 방법으로 불릴 수 있는 일반적인 솔루션을 원합니다.
2, 8, 16 이외의 베이스를 허용하고 싶다.
관련된
- Python의 int(string, base)의 우아한 역함수
- python의 재귀를 사용하여 base-x 시스템에 정수
- Python에서의 Base 62 변환
- Python에서 정수를 최단 URL-safe 문자열로 변환하는 방법은 무엇입니까?
놀랍게도, 사람들은 (영문 알파벳의 길이보다 작은) 작은 기수로 변환하는 해결책만 제공하고 있었다.2에서 무한대로 임의의 베이스로 변환하는 솔루션을 제공하려는 시도는 없었습니다.
매우 심플한 솔루션은 다음과 같습니다.
def numberToBase(n, b):
if n == 0:
return [0]
digits = []
while n:
digits.append(int(n % b))
n //= b
return digits[::-1]
577
,
numberToBase(67854 ** 15 - 102, 577)
[4, 473, 131, 96, 431, 285, 524, 486, 28, 23, 16, 82, 292, 538, 149, 25, 41, 483, 100, 517, 131, 28, 0, 435, 197, 264, 455]
,
나중에 원하는 베이스로 변환할 수 있습니다.
- 원하는 것을 하기 위한 내장 라이브러리 기능이 없는 경우가 있기 때문에 직접 작성해야 하는 경우가 있습니다.동의하지 않을 경우 기본 10 번호를 기본 577로 변환할 수 있는 기능이 내장된 솔루션을 게시합니다.
- 이는 어떤 기초에서 숫자가 무엇을 의미하는지 이해하지 못하기 때문입니다.
- n <= 36에 대해서만 메서드의 기본이 작동하는 이유를 잠시 생각해 보시기 바랍니다.작업을 마치면 내 함수가 목록을 반환하고 서명하는 이유를 알 수 있습니다.
오래된 버전의 Python과의 호환성이 필요한 경우 gmpy를 사용할 수 있습니다(빠르고 완전한 일반적인 int-to-string 변환 기능을 포함하고 있으며 이러한 오래된 버전을 위해 빌드할 수 있습니다). 최근 버전은 오래된 Python 및 GMP 릴리스에 대해 테스트되지 않았기 때문에 오래된 릴리스를 사용해 볼 필요가 있습니다.es) 또는 Python 코드를 사용합니다(예: Python 2의 경우).
import string
digs = string.digits + string.ascii_letters
def int2base(x, base):
if x < 0:
sign = -1
elif x == 0:
return digs[0]
else:
sign = 1
x *= sign
digits = []
while x:
digits.append(digs[int(x % base)])
x = int(x / base)
if sign < 0:
digits.append('-')
digits.reverse()
return ''.join(digits)
3, Python 3의 ,int(x / base)
결과를 '오류'로 .x // base
:
import string
digs = string.digits + string.ascii_letters
def int2base(x, base):
if x < 0:
sign = -1
elif x == 0:
return digs[0]
else:
sign = 1
x *= sign
digits = []
while x:
digits.append(digs[x % base])
x = x // base
if sign < 0:
digits.append('-')
digits.reverse()
return ''.join(digits)
"{0:b}".format(100) # bin: 1100100
"{0:x}".format(100) # hex: 64
"{0:o}".format(100) # oct: 144
def baseN(num,b,numerals="0123456789abcdefghijklmnopqrstuvwxyz"):
return ((num == 0) and numerals[0]) or (baseN(num // b, b, numerals).lstrip(numerals[0]) + numerals[num % b])
참조: http://code.activestate.com/recipes/65212/
이로 인해 다음과 같은 문제가 발생할 수 있습니다.
RuntimeError: maximum recursion depth exceeded in cmp
매우 큰 정수의 경우.
>>> numpy.base_repr(10, base=3)
'101'
:numpy.base_repr()
36번입니다. 이외의 는, 「」, 「」를 합니다.ValueError
재귀적
다음 항목에 대한 가장 많은 표를 얻은 답변을 단순화할 수 있습니다.
BS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def to_base(n, b):
return "0" if not n else to_base(n//b, b).lstrip("0") + BS[n%b]
같은 어드바이스로RuntimeError: maximum recursion depth exceeded in cmp
아주 큰 정수와 음수에서요. (사용할 수 있습니다sys.setrecursionlimit(new_limit)
.)
반복적
재귀 문제를 방지하려면:
BS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def to_base(s, b):
res = ""
while s:
res+=BS[s%b]
s//= b
return res[::-1] or "0"
좋은 답변입니다!제 질문에 대한 대답은 "아니오"였습니다. 명백한 해결책을 놓치고 있지 않았습니다.답변에 나타난 좋은 아이디어를 응축하는 기능을 소개합니다.
- 발신자가 제공한 문자 매핑 허용(base64 인코딩 포함)
- 음수 및 제로 체크
- 복잡한 숫자를 문자열의 튜플에 매핑합니다.
def int2base(x,b,alphabet='0123456789abcdefghijklmnopqrstuvwxyz'): 'convert an integer to its string representation in a given base' if b<2 or b>len(alphabet): if b==64: # assume base64 rather than raise error alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" else: raise AssertionError("int2base base out of range") if isinstance(x,complex): # return a tuple return ( int2base(x.real,b,alphabet) , int2base(x.imag,b,alphabet) ) if x<=0: if x==0: return alphabet[0] else: return '-' + int2base(-x,b,alphabet) # else x is non-negative real rets='' while x>0: x,idx = divmod(x,b) rets = alphabet[idx] + rets return rets
하면 .baseconv.py
프로젝트: https://github.com/semente/python-baseconv
사용 예:
>>> from baseconv import BaseConverter
>>> base20 = BaseConverter('0123456789abcdefghij')
>>> base20.encode(1234)
'31e'
>>> base20.decode('31e')
'1234'
>>> base20.encode(-1234)
'-31e'
>>> base20.decode('-31e')
'-1234'
>>> base11 = BaseConverter('0123456789-', sign='$')
>>> base11.encode('$1234')
'$-22'
>>> base11.decode('$-22')
'$1234'
Bultin 는 몇 가지 .baseconv.base2
,baseconv.base16
★★★★★★★★★★★★★★★★★」baseconv.base64
.
def base(decimal ,base) :
list = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
other_base = ""
while decimal != 0 :
other_base = list[decimal % base] + other_base
decimal = decimal / base
if other_base == "":
other_base = "0"
return other_base
print base(31 ,16)
출력:
'1층'
http://code.activestate.com/recipes/65212/
def base10toN(num,n):
"""Change a to a base-n number.
Up to base-36 is supported without special notation."""
num_rep={10:'a',
11:'b',
12:'c',
13:'d',
14:'e',
15:'f',
16:'g',
17:'h',
18:'i',
19:'j',
20:'k',
21:'l',
22:'m',
23:'n',
24:'o',
25:'p',
26:'q',
27:'r',
28:'s',
29:'t',
30:'u',
31:'v',
32:'w',
33:'x',
34:'y',
35:'z'}
new_num_string=''
current=num
while current!=0:
remainder=current%n
if 36>remainder>9:
remainder_string=num_rep[remainder]
elif remainder>=36:
remainder_string='('+str(remainder)+')'
else:
remainder_string=str(remainder)
new_num_string=remainder_string+new_num_string
current=current/n
return new_num_string
여기 같은 링크의 다른 것이 있습니다.
def baseconvert(n, base):
"""convert positive decimal integer n to equivalent in another base (2-36)"""
digits = "0123456789abcdefghijklmnopqrstuvwxyz"
try:
n = int(n)
base = int(base)
except:
return ""
if n < 0 or base < 2 or base > 36:
return ""
s = ""
while 1:
r = n % base
s = digits[r] + s
n = n / base
if n == 0:
break
return s
이걸 위한 pip 패키지를 만들었어요.
내 베이스를 사용하는 것을 추천한다.py https://github.com/kamijoutouma/bases.py은 베이스에서 영감을 얻은 것입니다.js
from bases import Bases
bases = Bases()
bases.toBase16(200) // => 'c8'
bases.toBase(200, 16) // => 'c8'
bases.toBase62(99999) // => 'q0T'
bases.toBase(200, 62) // => 'q0T'
bases.toAlphabet(300, 'aAbBcC') // => 'Abba'
bases.fromBase16('c8') // => 200
bases.fromBase('c8', 16) // => 200
bases.fromBase62('q0T') // => 99999
bases.fromBase('q0T', 62) // => 99999
bases.fromAlphabet('Abba', 'aAbBcC') // => 300
사용 가능한 베이스에 대해서는, https://github.com/kamijoutouma/bases.py#known-basesalphabets 를 참조해 주세요.
편집: pip link https://pypi.python.org/pypi/bases.py/0.2.2
def base_conversion(num, base):
digits = []
while num > 0:
num, remainder = divmod(num, base)
digits.append(remainder)
return digits[::-1]
>>> import string
>>> def int2base(integer, base):
if not integer: return '0'
sign = 1 if integer > 0 else -1
alphanum = string.digits + string.ascii_lowercase
nums = alphanum[:base]
res = ''
integer *= sign
while integer:
integer, mod = divmod(integer, base)
res += nums[mod]
return ('' if sign == 1 else '-') + res[::-1]
>>> int2base(-15645, 23)
'-16d5'
>>> int2base(213, 21)
'a3'
관심 있는 사람들을 위한 재귀적 해결책입니다.물론 음의 바이너리 값에서는 동작하지 않습니다.Two's Completment를 구현해야 합니다.
def generateBase36Alphabet():
return ''.join([str(i) for i in range(10)]+[chr(i+65) for i in range(26)])
def generateAlphabet(base):
return generateBase36Alphabet()[:base]
def intToStr(n, base, alphabet):
def toStr(n, base, alphabet):
return alphabet[n] if n < base else toStr(n//base,base,alphabet) + alphabet[n%base]
return ('-' if n < 0 else '') + toStr(abs(n), base, alphabet)
print('{} -> {}'.format(-31, intToStr(-31, 16, generateAlphabet(16)))) # -31 -> -1F
def int2base(a, base, numerals="0123456789abcdefghijklmnopqrstuvwxyz"):
baseit = lambda a=a, b=base: (not a) and numerals[0] or baseit(a-a%b,b*base)+numerals[a%b%(base-1) or (a%b) and (base-1)]
return baseit()
설명.
에서나 모든 . a1+a2*base**2+a3*base**3...
미션'를 찾는 입니다.
★★★★★★★★★★★★★★★★★에 대해서N=1,2,3...
입니다.aN*base**N
moudling b에 moudling에 mouldingb=base**(N+1)
N보다 .또한 으로써 n을 줄입니다.aN*base**N
.
base%(base-1)==1 for base**p%(base-1)==1 및 그에 따른 q*base^p%(base-1)==q. 단, q=base-1은 0을 반환한다.func가 체크하고 있는0 을 반환했을 경우에 그것을 수정하려면 , 0 이 되어 버립니다.
이점
이 표본에서는 하나의 곱셈(나눗셈의 제곱)과 비교적 적은 시간이 걸리는 몇 개의 곱셈만 있다.
def base_changer(number,base):
buff=97+abs(base-10)
dic={};buff2='';buff3=10
for i in range(97,buff+1):
dic[buff3]=chr(i)
buff3+=1
while(number>=base):
mod=int(number%base)
number=int(number//base)
if (mod) in dic.keys():
buff2+=dic[mod]
continue
buff2+=str(mod)
if (number) in dic.keys():
buff2+=dic[number]
else:
buff2+=str(number)
return buff2[::-1]
다음으로 임의의 베이스의 수를 다른 베이스로 변환하는 예를 나타냅니다.
from collections import namedtuple
Test = namedtuple("Test", ["n", "from_base", "to_base", "expected"])
def convert(n: int, from_base: int, to_base: int) -> int:
digits = []
while n:
(n, r) = divmod(n, to_base)
digits.append(r)
return sum(from_base ** i * v for i, v in enumerate(digits))
if __name__ == "__main__":
tests = [
Test(32, 16, 10, 50),
Test(32, 20, 10, 62),
Test(1010, 2, 10, 10),
Test(8, 10, 8, 10),
Test(150, 100, 1000, 150),
Test(1500, 100, 10, 1050000),
]
for test in tests:
result = convert(*test[:-1])
assert result == test.expected, f"{test=}, {result=}"
print("PASSED!!!")
14를 2로 변환한다고 칩시다.몫이 0이 될 때까지 나눗셈 알고리즘을 반복합니다.
14 = 2 x 7
7 = 2 x 3 + 1
3 = 2 x 1 + 1
1 = 2 x 0 + 1
바이너리 표현은 아래에서 위로 읽어낸 나머지에 불과합니다.이것은 확장함으로써 증명될 수 있다.
14 = 2 x 7 = 2 x (2 x 3 + 1) = 2 x (2 x 1 + 1) = 2 x (2 x (2 x 0 + 1) + 1) = 2 ^3 + 2 + 2
코드는 상기 알고리즘의 실장입니다.
def toBaseX(n, X):
strbin = ""
while n != 0:
strbin += str(n % X)
n = n // X
return strbin[::-1]
이게 내 접근법이야처음에는 숫자를 변환한 후 문자열로 캐스팅합니다.
def to_base(n, base):
if base == 10:
return n
result = 0
counter = 0
while n:
r = n % base
n //= base
result += r * 10**counter
counter+=1
return str(result)
다른 베이스로 인코딩할 때 사용하는 이 함수를 작성했습니다.또한 결과를 '오프셋' 값으로 전환하는 방법도 제공했습니다.이것은 64보다 큰 글자로 인코딩하고 표시 가능한 문자(예: 95)를 유지하는 경우에 유용합니다.
또, 출력의 「목록」을 되돌리는 것을 피하고, 컴퓨팅 조작을 최소한으로 억제하려고 했습니다.pow(base) 배열은 온 디맨드로 계산되며 함수에 대한 추가 호출을 위해 유지됩니다.
출력은 바이너리 문자열입니다.
pows = {}
######################################################
def encode_base(value,
base = 10,
offset = 0) :
"""
Encode value into a binary string, according to the desired base.
Input :
value : Any positive integer value
offset : Shift the encoding (eg : Starting at chr(32))
base : The base in which we'd like to encode the value
Return : Binary string
Example : with : offset = 32, base = 64
100 -> !D
200 -> #(
"""
# Determine the number of loops
try :
pb = pows[base]
except KeyError :
pb = pows[base] = {n : base ** n for n in range(0, 8) if n < 2 ** 48 -1}
for n in pb :
if value < pb[n] :
n -= 1
break
out = []
while n + 1 :
b = pb[n]
out.append(chr(offset + value // b))
n -= 1
value %= b
return ''.join(out).encode()
이 함수는 임의의 정수를 임의의 베이스에서 임의의 베이스로 변환합니다.
def baseconvert(number, srcbase, destbase):
if srcbase != 10:
sum = 0
for _ in range(len(str(number))):
sum += int(str(number)[_]) * pow(srcbase, len(str(number)) - _ - 1)
b10 = sum
return baseconvert(b10, 10, destbase)
end = ''
q = number
while(True):
r = q % destbase
q = q // destbase
end = str(r) + end
if(q<destbase):
end = str(q) + end
return int(end)
아래에 제공된 Python 코드는 Python 정수를 임의의 베이스(최대 2 ~무한)의 문자열로 변환하여 양방향으로 작동합니다.따라서 정수 대신 N에 문자열을 제공하여 생성된 모든 문자열을 Python 정수로 변환할 수 있습니다.코드는 의도적으로 양수에 대해서만 동작합니다(음수값과 그 비트 표현에 대해 파고들고 싶지 않은 번거로움이 있습니다).필요한 것, 필요한 것, 마음에 드는 것을 이 코드에서 선택해 주세요.또, 이용 가능한 옵션에 대해서도 즐겁게 학습할 수 있습니다.이용 가능한 다양한 접근 방식을 모두 문서화하기 위한 목적으로만 많은 것이 존재합니다(예: Oneliner는 약속된 경우에도 속도가 빠르지 않은 것 같습니다).
나는 살바도르 달리가 제안한 무한대 베이스 포맷을 좋아한다.간단한 바이너리 비트 표현에도 광학적으로 잘 작동하는 멋진 제안입니다.infiniteBase=의 경우 width=x padding 파라미터에 주의해 주십시오.진정한 형식의 문자열은 숫자 전체에 적용되는 것이 아니라 숫자에 적용됩니다.코드 처리 infiniteBase digits 형식이 다른 옵션보다 조금 더 빠르게 실행된다고 생각되는데, 또 다른 이유는 무엇입니까?
유니코드를 사용하여 숫자에 사용할 수 있는 기호의 수를 확장하는 것은 마음에 들지 않습니다.따라서 아래 코드는 없습니다.대신 제안된 infiniteBase 형식을 사용하거나 정수를 바이트로 저장하여 압축하십시오.
def inumToStr( N, base=2, width=1, infiniteBase=False,\
useNumpy=False, useRecursion=False, useOneliner=False, \
useGmpy=False, verbose=True):
''' Positive numbers only, but works in BOTH directions.
For strings in infiniteBase notation set for bases <= 62
infiniteBase=True . Examples of use:
inumToStr( 17, 2, 1, 1) # [1,0,0,0,1]
inumToStr( 17, 3, 5) # 00122
inumToStr(245, 16, 4) # 00F5
inumToStr(245, 36, 4,0,1) # 006T
inumToStr(245245245245,36,10,0,1) # 0034NWOQBH
inumToStr(245245245245,62) # 4JhA3Th
245245245245 == int(gmpy2.mpz('4JhA3Th',62))
inumToStr(245245245245,99,2) # [25,78, 5,23,70,44]
----------------------------------------------------
inumToStr( '[1,0,0,0,1]',2, infiniteBase=True ) # 17
inumToStr( '[25,78, 5,23,70,44]', 99) # 245245245245
inumToStr( '0034NWOQBH', 36 ) # 245245245245
inumToStr( '4JhA3Th' , 62 ) # 245245245245
----------------------------------------------------
--- Timings for N = 2**4096, base=36:
standard: 0.0023
infinite: 0.0017
numpy : 0.1277
recursio; 0.0022
oneliner: 0.0146
For N = 2**8192:
standard: 0.0075
infinite: 0.0053
numpy : 0.1369
max. recursion depth exceeded: recursio/oneliner
'''
show = print
if type(N) is str and ( infiniteBase is True or base > 62 ):
lstN = eval(N)
if verbose: show(' converting a non-standard infiniteBase bits string to Python integer')
return sum( [ item*base**pow for pow, item in enumerate(lstN[::-1]) ] )
if type(N) is str and base <= 36:
if verbose: show('base <= 36. Returning Python int(N, base)')
return int(N, base)
if type(N) is str and base <= 62:
if useGmpy:
if verbose: show(' base <= 62, useGmpy=True, returning int(gmpy2.mpz(N,base))')
return int(gmpy2.mpz(N,base))
else:
if verbose: show(' base <= 62, useGmpy=False, self-calculating return value)')
lstStrOfDigits="0123456789"+ \
"abcdefghijklmnopqrstuvwxyz".upper() + \
"abcdefghijklmnopqrstuvwxyz"
dictCharToPow = {}
for index, char in enumerate(lstStrOfDigits):
dictCharToPow.update({char : index})
return sum( dictCharToPow[item]*base**pow for pow, item in enumerate(N[::-1]) )
#:if
#:if
if useOneliner and base <= 36:
if verbose: show(' base <= 36, useOneliner=True, running the Oneliner code')
d="0123456789abcdefghijklmnopqrstuvwxyz"
baseit = lambda a=N, b=base: (not a) and d[0] or \
baseit(a-a%b,b*base)+d[a%b%(base-1) or (a%b) and (base-1)]
return baseit().rjust(width, d[0])[1:]
if useRecursion and base <= 36:
if verbose: show(' base <= 36, useRecursion=True, running recursion algorythm')
BS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
def to_base(n, b):
return "0" if not n else to_base(n//b, b).lstrip("0") + BS[n%b]
return to_base(N, base).rjust(width,BS[0])
if base > 62 or infiniteBase:
if verbose: show(' base > 62 or infiniteBase=True, returning a non-standard digits string')
# Allows arbitrary large base with 'width=...'
# applied to each digit (useful also for bits )
N, digit = divmod(N, base)
strN = str(digit).rjust(width, ' ')+']'
while N:
N, digit = divmod(N, base)
strN = str(digit).rjust(width, ' ') + ',' + strN
return '[' + strN
#:if
if base == 2:
if verbose: show(" base = 2, returning Python str(f'{N:0{width}b}')")
return str(f'{N:0{width}b}')
if base == 8:
if verbose: show(" base = 8, returning Python str(f'{N:0{width}o}')")
return str(f'{N:0{width}o}')
if base == 16:
if verbose: show(" base = 16, returning Python str(f'{N:0{width}X}')")
return str(f'{N:0{width}X}')
if base <= 36:
if useNumpy:
if verbose: show(" base <= 36, useNumpy=True, returning np.base_repr(N, base)")
import numpy as np
strN = np.base_repr(N, base)
return strN.rjust(width, '0')
else:
if verbose: show(' base <= 36, useNumpy=False, self-calculating return value)')
lstStrOfDigits="0123456789"+"abcdefghijklmnopqrstuvwxyz".upper()
strN = lstStrOfDigits[N % base] # rightmost digit
while N >= base:
N //= base # consume already converted digit
strN = lstStrOfDigits[N % base] + strN # add digits to the left
#:while
return strN.rjust(width, lstStrOfDigits[0])
#:if
#:if
if base <= 62:
if useGmpy:
if verbose: show(" base <= 62, useGmpy=True, returning gmpy2.digits(N, base)")
import gmpy2
strN = gmpy2.digits(N, base)
return strN.rjust(width, '0')
# back to Python int from gmpy2.mpz with
# int(gmpy2.mpz('4JhA3Th',62))
else:
if verbose: show(' base <= 62, useGmpy=False, self-calculating return value)')
lstStrOfDigits= "0123456789" + \
"abcdefghijklmnopqrstuvwxyz".upper() + \
"abcdefghijklmnopqrstuvwxyz"
strN = lstStrOfDigits[N % base] # rightmost digit
while N >= base:
N //= base # consume already converted digit
strN = lstStrOfDigits[N % base] + strN # add digits to the left
#:while
return strN.rjust(width, lstStrOfDigits[0])
#:if
#:if
#:def
2에서 9까지의 베이스를 대상으로 한 「최적화되지 않은」솔루션을 소개합니다.
def to_base(N, base=2):
N_in_base = ''
while True:
N_in_base = str(N % base) + N_in_base
N //= base
if N == 0:
break
return N_in_base
이 솔루션에서는 최종 결과를 되돌릴 필요는 없지만 실제로는 최적화되어 있지 않습니다.그 이유에 대해서는, 다음의 회답을 참조해 주세요.https://stackoverflow.com/a/37133870/7896998
간단한 기본 변환
def int_to_str(x, b):
s = ""
while x:
s = str(x % b) + s
x //= b
return s
0부터 9까지의 출력 예
s = ""
x = int(input())
while x:
if x % 9 == 0:
s = "9" + s
x -= x % 10
x = x // 9
else:
s = str(x % 9) + s
x = x // 9
print(s)
def dec_to_radix(input, to_radix=2, power=None):
if not isinstance(input, int):
raise TypeError('Not an integer!')
elif power is None:
power = 1
if input == 0:
return 0
else:
remainder = input % to_radix**power
digit = str(int(remainder/to_radix**(power-1)))
return int(str(dec_to_radix(input-remainder, to_radix, power+1)) + digit)
def radix_to_dec(input, from_radix):
if not isinstance(input, int):
raise TypeError('Not an integer!')
return sum(int(digit)*(from_radix**power) for power, digit in enumerate(str(input)[::-1]))
def radix_to_radix(input, from_radix=10, to_radix=2, power=None):
dec = radix_to_dec(input, from_radix)
return dec_to_radix(dec, to_radix, power)
또 다른 짧은 내용(이모도 이해하기 쉬움):
def int_to_str(n, b, symbols='0123456789abcdefghijklmnopqrstuvwxyz'):
return (int_to_str(n/b, b, symbols) if n >= b else "") + symbols[n%b]
적절한 예외 처리와 함께:
def int_to_str(n, b, symbols='0123456789abcdefghijklmnopqrstuvwxyz'):
try:
return (int_to_str(n/b, b) if n >= b else "") + symbols[n%b]
except IndexError:
raise ValueError(
"The symbols provided are not enough to represent this number in "
"this base")
다음은 부호 있는 정수와 사용자 지정 숫자를 처리하는 재귀 버전입니다.
import string
def base_convert(x, base, digits=None):
"""Convert integer `x` from base 10 to base `base` using `digits` characters as digits.
If `digits` is omitted, it will use decimal digits + lowercase letters + uppercase letters.
"""
digits = digits or (string.digits + string.ascii_letters)
assert 2 <= base <= len(digits), "Unsupported base: {}".format(base)
if x == 0:
return digits[0]
sign = '-' if x < 0 else ''
x = abs(x)
first_digits = base_convert(x // base, base, digits).lstrip(digits[0])
return sign + first_digits + digits[x % base]
숫자 표시에는 문자열만 있는 것이 아닙니다.정수 목록을 사용하여 각 자릿수의 순서를 표시할 수 있습니다.그것들은 쉽게 문자열로 변환할 수 있습니다.
어떤 응답도 base < 2 를 거부하지 않습니다.대부분의 응답은 매우 느리게 실행되거나 매우 큰 번호(56789 * 43210 등)의 스택오버플로우와 함께 크래시 됩니다.이러한 장애를 방지하려면 다음과 같이 신속하게 줄이십시오.
def n_to_base(n, b):
if b < 2: raise # invalid base
if abs(n) < b: return [n]
ret = [y for d in n_to_base(n, b*b) for y in divmod(d, b)]
return ret[1:] if ret[0] == 0 else ret # remove leading zeros
def base_to_n(v, b):
h = len(v) // 2
if h == 0: return v[0]
return base_to_n(v[:-h], b) * (b**h) + base_to_n(v[-h:], b)
assert ''.join(['0123456789'[x] for x in n_to_base(56789**43210,10)])==str(56789**43210)
에서는, 「」n_to_base
에 필적하는str
수에서는 0.에 요, (0.3초 정도)와hex
놀라실 수도 있습니다(내 기계에서는 약 0.3ms, 1000배 이상 빠릅니다).그 이유는 큰 정수가 베이스 256(바이트)의 메모리에 저장되기 때문입니다.각 바이트는 단순히 2글자의 16진수 문자열로 변환할 수 있습니다.이 정렬은 2의 거듭제곱인 베이스에서만 발생합니다., 2,8 16 16 ( base 64 , asciii , utf 16 , utf 32 ) 。
10진수 문자열의 마지막 숫자를 고려합니다.정수를 형성하는 바이트 시퀀스와는 어떤 관계가 있습니까? 이번에는 을 붙이자.s[i]
s[0]
가장 중요하지 않은(리틀 엔디안) 존재입니다. 후 는 '''입니다.sum([s[i]*(256**i) % 10 for i in range(n)])
는 i ( 자릿수는 256**i i > 0 (6*6=36)이 됩니다.(s[0]*5 + sum(s)*6)%10
여기서 마지막 숫자는 모든 바이트의 합계에 의존함을 알 수 있습니다.이 비로컬 속성 때문에 10진수로 변환하기 어렵습니다.
def baseConverter(x, b):
s = ""
d = string.printable.upper()
while x > 0:
s += d[x%b]
x = x / b
return s[::-1]
num = input("number")
power = 0
num = int(num)
while num > 10:
num = num / 10
power += 1
print(str(round(num, 2)) + "^" + str(power))
언급URL : https://stackoverflow.com/questions/2267362/how-to-convert-an-integer-to-a-string-in-any-base
'programing' 카테고리의 다른 글
VueJS-컴포넌트 재렌더 구현에 도움이 필요함 (0) | 2022.10.02 |
---|---|
여러 MySQL 행을 하나의 필드에 연결할 수 있습니까? (0) | 2022.10.02 |
java: 지정된 초수 후에 함수를 실행합니다. (0) | 2022.10.02 |
따옴표와 괄호가 있는 경우와 없는 경우의 set Timeout의 차이 (0) | 2022.10.02 |
SQL: 행 순서 위치를 변경하는 방법 (0) | 2022.10.02 |