Let’s discuss the logic to convert a number into binary, octal, and hexadecimal. Generally, in other languages, it is hard to convert a number into binary octal and hexadecimal, but in the python language, we have, we have pre-built functions in order to perform the conversion.
“bin” keyword is used to convert a number into a binary number. The “oct” keyword is used to convert a number into an octal and, we use the “hex” keyword to convert a number into a hexadecimal number.
k = 4
print("original", k)
print(bin(k), "After binary conversion")
print(oct(k), "After octal conversion")
print(hex(k), "After hexadecimal conversion")
Output:
original 4 0b100 After binary conversion 0o4 After octal conversion 0x4 After hexadecimal conversion
Explanation
In this example, we have initialized a variable k with the 4. Next, we used the print statement in order to print the original number. Then, we printed the converted binary number of the original value using the bin function.
Similarly, oct() and hex() functions to convert to octal and hexadecimal respectively.
Conclusion
We can conclude that now we know the logic and the different types of functions to convert a number into binary, octal, and hexadecimal respectively.