本文介紹了在 python 中添加二進制數時需要幫助的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
如果我有 2 個二進制形式的數字作為字符串,并且我想將它們相加,我將從最右邊開始逐位添加.所以 001 + 010 = 011但是假設我必須做 001+001,我應該如何創建代碼來弄清楚如何接管響應?
If I have 2 numbers in binary form as a string, and I want to add them I will do it digit by digit, from the right most end. So 001 + 010 = 011 But suppose I have to do 001+001, how should I create a code to figure out how to take carry over responses?
推薦答案
bin
和 int
在這里非常有用:
bin
and int
are very useful here:
a = '001'
b = '011'
c = bin(int(a,2) + int(b,2))
# 0b100
int
允許您在從字符串(在本例中為兩個)轉換時指定第一個參數的基數,而 bin
將數字轉換回二進制字符串.
int
allows you to specify what base the first argument is in when converting from a string (in this case two), and bin
converts a number back to a binary string.
這篇關于在 python 中添加二進制數時需要幫助的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!