반응형
파이썬에서 십진수를 이진수로 변환
이 질문에는 이미 답변이 있습니다.
- 이진 문자열에 파이썬 int? 답변 32 개
파이썬에서 십진수를 이진수로 변환하는 데 사용할 수있는 모듈이나 함수가 있습니까? 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))
완료를 위해 : 고정 소수점 표현을 이진으로 변환하려면 다음 작업을 수행 할 수 있습니다.
정수와 분수 부분을 가져옵니다.
from decimal import * a = Decimal(3.625) a_split = (int(a//1),a%1)
소수 부분을 이진 표현으로 변환하십시오. 이를 달성하려면 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
반응형
'development' 카테고리의 다른 글
Capybara에서 확인란을 확인하는 방법은 무엇입니까? (0) | 2020.07.11 |
---|---|
null 값을 확인하는 올바른 방법은 무엇입니까? (0) | 2020.07.11 |
'자바'는 내부 또는 외부 명령으로 인식되지 않습니다 (0) | 2020.07.11 |
누락 된 IIS Express SSL 인증서를 어떻게 복원합니까? (0) | 2020.07.11 |
쉼표로 구분 된 std :: string 구문 분석 (0) | 2020.07.11 |