English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

تحويل من ثنائي إلى عشري والعكس صحيح في Python

المهمة لدينا هي تحويل عدد عشري إلى عدد ثنائي، وتحويل عدد ثنائي إلى عدد عشري.

الخوارزمية

Bintodec()

Step1: Enter binary number.
Step2: Next take the length of the binary number.
Step3: Using for loop we convert binary to a decimal number.
Just like if the binary number is 1111, then the calculation would be
1*2**3+1*2**2+1*2**1+1*2**0 = 15
Step4: Display the number.

Dectobin()

Step1: Enter the decimal number.
Step2: Using while loop
*Divide the number it by 2. Find both remainder and quotient. Take another variable initialized with 1.
Now remainder will be multiplied with this variable and added with the final output number. That variable will be incremented by 1.
*The first remainder is the last digit in the sequence.
Step3: Display the value.

范例程式码

print("*****************************************************")
print(" DECIMAL TO BINARY AND BINARY TO DECIMAL CONVERSION")
print("*****************************************************")
print(" لتحويل العشري إلى الثنائي... اضغط على 1.")
print(" لتحويل الثنائي إلى العشري... اضغط على 2")
print("*****************************************************")
my_choice=int(input("Enter your choice: "))
if my_choice==1:
i=1
s=0
my_dec=int(input("Enter decimal to be converted: "))
while my_dec>0:
   rem=int(my_dec%2)
   s=s+(i*rem)
   my_dec=int(my_dec/2)
   i=i*10
   print("الرقم الثنائي للعدد المحدد هو ", s, ".")
else:
   my_bin=input('أدخل الثنائي الذي سيتم تحويله: ')
   n=len(my_bin)
   res=0
للمسلسل i في المدى(1, n+1):
   res=res+int(my_bin[i-1])*2**(n-i)
print("العدد العشري للرقم الثنائي المحدد هو ", res, ".")
print("******************************************************")

النتيجة

*****************************************************
تحويل العشري إلى الثنائي والثنائي إلى العشري
*****************************************************
print(" لتحويل العشري إلى الثنائي... اضغط على 1.")
print(" لتحويل الثنائي إلى العشري... اضغط على 2")
*****************************************************
أدخل اختيارك: 1
أدخل العشري الذي سيتم تحويله: 15
الرقم الثنائي للعدد المحدد هو 1111.
******************************************************
*****************************************************
تحويل العشري إلى الثنائي والثنائي إلى العشري
*****************************************************
لتحويل العشري إلى الثنائي... اضغط على 1.
لتحويل الثنائي إلى العشري... اضغط على 2
*****************************************************
أدخل اختيارك: 2
أدخل الثنائي الذي سيتم تحويله: 1111
العدد العشري للرقم الثنائي المحدد هو 15.
******************************************************
سيذهب إليك هذا