23
loading...
This website collects cookies to deliver better user experience
1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
---|---|---|---|---|---|---|---|
2^7 | 2^6 | 2^5 | 2^4 | 2^3 | 2^2 | 2^1 | 2^0 |
128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |
1 | 0 | 1 | 1 | 0 | 0 | 1 | 1 |
---|---|---|---|---|---|---|---|
2^7 | 2^6 | 2^5 | 2^4 | 2^3 | 2^2 | 2^1 | 2^0 |
128 | 32 | 16 | 2 | 1 |
1 + 2 + 16 + 32 + 128 = 179
def bin_to_dec(bin_string):
decimal = 0
# Initialize our rightmost power of 2 (2^0)
power_of_2 = pow(2, 0);
# Iterate through the reversed binary string (R -> L)
for b in bin_string[::-1]:
# If the digit is 1
if int(b) == 1:
# Add the power of 2 to our decimal number
decimal += power_of_2
# Double the power of 2 for the next place
power_of_2 *= 2
# Output the result
return decimal
# Prints 179
print(bin_to_dec("10110011"))
179 / 2 = 89R1
_______1
89 / 2 = 44R1
______11
44 / 2 = 22R0
_____011
22 / 2 = 11R0
____0011
11 / 2 = 5R1
___10011
5 / 2 = 2R1
__110011
2 / 2 = 1R0
_0110011
1 / 2 = 0R1
10110011
def dec_to_bin(decimal):
bin_string = ""
power_of_2 = pow(2, 0)
while decimal > 0:
# The remainder of dividing by 2 is the next bin digit
bin_digit = decimal % 2
# Divide the decimal by two (floor division)
decimal //= 2
# Prepend digit to string w/string concatenation
bin_string = str(bin_digit) + bin_string
# Double the power of 2 for the next place
power_of_2 *= 2
# Output the result
return bin_string
# Prints "10110111"
print(dec_to_bin(179))
The code below uses Python's ord()
and chr()
functions which are used to convert ASCII letters to numbers and back.
def n_to_dec(n_string, n):
decimal = 0
power_of_n = pow(n, 0);
for b in n_string[::-1]:
# A = 10, B = 11, C = 12 ...
b = ord(b) - 65 + 10 if not b.isdigit() else int(b)
if int(b) != 0:
decimal += int(b) * power_of_n
power_of_n *= n
return decimal
# Prints 255
print(n_to_dec("FF", 16))
def dec_to_n(decimal, n):
n_string = ""
power_of_n = pow(n, 0)
while decimal > 0:
n_digit = decimal % n
# 10 = A, 11 = B, 12 = C ...
n_digit = chr(65 - 10 + n_digit) if n_digit >= 10 else n_digit
decimal //= n
n_string = str(n_digit) + n_string
power_of_n *= n
return n_string
# Prints FF
print(dec_to_n(255, 16))
0123456789ABCDEF
. For example:0011 = 3
0110 = 6
1100 = C (12)
10100101 (bin)
1010 | 0101 |
---|---|
A | 5 |
A5 (hex)
bin()
and hex()
that will do these conversions, but it's useful to know how the process works yourself so you can do a quick conversion when needed. Now, the next time you see a color written as #FFFFFF
, you will know that each RGB value is 255 and the lights are all on (making white). Hope you found this helpful!