DEV Community

Kiruthiga S
Kiruthiga S

Posted on

Python

Binary
base value is 2,it uses 2 digits i.e. 0 and 1

Decimal
base value is 10, it uses digits i.e. 0-1
eg:12265
(1×10^4) + (2×10^3) + (2×10^2) + (6×10^1) + (5×10^0)
= (1×10000) + (2×1000) + (2×100) + (6×10) + (5×1)
= 10000 + 2000 + 200 + 60 + 5
= 12265

Octal
base value is 8 , it uses 8 digits i.e. 0-7
eg:25
25₈ = (2 × 8¹) + (5 × 8⁰)
= (2 × 8) + (5 × 1)
= 16 + 5
= 21₁₀

Hexadecimal
base value is 16 , it uses 16 digits i.e. from 10-15 are represented as A-F i.e. 10 is represented as A, 11 as B, 12 as C, 13 as D, 14 as E, and 15 as F
eg:2B₁₆
2B₁₆ = (2 × 16¹) + (11 × 16⁰)
= (2 × 16) + (11 × 1)
= 32 + 11
= 43₁₀

Binary to decimal

def binary_to_decimal(binary):
    decimal = 0
    power = 1
    while binary > 0:
        digit = binary % 10
        decimal = decimal + digit * power
        power =power*2
        binary = binary // 10
    print("Decimal =", decimal)
num = int(input("Enter a binary number: "))
binary_to_decimal(num)
Enter fullscreen mode Exit fullscreen mode

Output:
Enter a binary number: 1010
Decimal = 10

Decimal to Binary

def decimal_to_binary(num):
    binary = ""
    while num > 0:
        digit = num % 2
        binary = str(digit) + binary
        num = num // 2
    print("Binary =", binary)
num = int(input("Enter a decimal number: "))
decimal_to_binary(num)
Enter fullscreen mode Exit fullscreen mode

Output:
Enter a decimal number: 5
Binary = 101

Binary to Octal

def binary_to_octal(binary):
    decimal = 0
    power = 1
    while binary > 0:
        digit = binary % 10
        decimal = decimal + digit * power
        power = power * 2
        binary = binary // 10
    octal = ""
    while decimal > 0:
        digit = decimal % 8
        octal = str(digit) + octal
        decimal = decimal // 8
    print("Octal =", octal)
num = int(input("Enter binary number: "))
binary_to_octal(num)
Enter fullscreen mode Exit fullscreen mode

Output:
Enter binary number: 1010
Octal = 12

Top comments (0)