development

파이썬에서 십진수를 이진수로 변환

big-blog 2020. 7. 11. 08:54
반응형

파이썬에서 십진수를 이진수로 변환


이 질문에는 이미 답변이 있습니다.

파이썬에서 십진수를 이진수로 변환하는 데 사용할 수있는 모듈이나 함수가 있습니까? int ( '[binary_value]', 2)를 사용하여 이진수를 십진수로 변환 할 수 있으므로 직접 코드를 작성하지 않고 반대로 할 수 있습니까?


모든 숫자는 이진수로 저장됩니다. 이진수로 주어진 숫자의 텍스트 표현을 원한다면bin(i)

>>> bin(10)
'0b1010'
>>> 0b1010
10

"{0:#b}".format(my_int)

앞에 0b가 없으면 :

"{0:b}".format(int)

Python 3.6부터는 형식화 된 문자열 리터럴 또는 f-string , --- PEP 를 사용할 수도 있습니다 .

f"{int:b}"

def dec_to_bin(x):
    return int(bin(x)[2:])

그렇게 쉽습니다.


numpy 모듈에서 함수를 사용할 수도 있습니다

from numpy import binary_repr

선행 0을 처리 할 수도 있습니다.

Definition:     binary_repr(num, width=None)
Docstring:
    Return the binary representation of the input number as a string.

    This is equivalent to using base_repr with base 2, but about 25x
    faster.

    For negative numbers, if width is not given, a - sign is added to the
    front. If width is given, the two's complement of the number is
    returned, with respect to that width.

@aaronasterling의 답변에 동의합니다. 그러나 int로 캐스트 할 수있는 이진이 아닌 문자열을 원하면 표준 알고리즘을 사용할 수 있습니다.

def decToBin(n):
    if n==0: return ''
    else:
        return decToBin(n/2) + str(n%2)

n=int(input('please enter the no. in decimal format: '))
x=n
k=[]
while (n>0):
    a=int(float(n%2))
    k.append(a)
    n=(n-a)/2
k.append(0)
string=""
for j in k[::-1]:
    string=string+str(j)
print('The binary no. for %d is %s'%(x, string))

완료를 위해 : 고정 소수점 표현을 이진으로 변환하려면 다음 작업을 수행 할 수 있습니다.

  1. 정수와 분수 부분을 가져옵니다.

    from decimal import *
    a = Decimal(3.625)
    a_split = (int(a//1),a%1)
    
  2. 소수 부분을 이진 표현으로 변환하십시오. 이를 달성하려면 2를 연속적으로 곱하십시오.

    fr = a_split[1]
    str(int(fr*2)) + str(int(2*(fr*2)%1)) + ...
    

여기 에서 설명을 읽을 수 있습니다 .

참고 URL : https://stackoverflow.com/questions/3528146/convert-decimal-to-binary-in-python

반응형