How can I perform a conversion of a binary string to the corresponding hex value in Python?
I have 0000 0100 1000 1101
and I want to get 048D
I'm using Python 2.6.
Source Code # Python program to convert decimal into other number systems dec = 344 print("The decimal value of", dec, "is:") print(bin(dec), "in binary.") print(oct(dec), "in octal.") print(hex(dec), "in hexadecimal.") The decimal value of 344 is: 0b101011000 in binary. 0o530 in octal.
int
given base 2 and then hex
:
>>> int('010110', 2) 22 >>> hex(int('010110', 2)) '0x16' >>> >>> hex(int('0000010010001101', 2)) '0x48d'
The doc of int
:
int(x[, base]) -> integer Convert a string or number to an integer, if possible. A floating
point argument will be truncated towards zero (this does not include a string representation of a floating point number!) When converting a string, use the optional base. It is an error to supply a base when converting a non-string. If base is zero, the proper base is guessed based on the string content. If the argument is outside the integer range a long object will be returned instead.
The doc of hex
:
hex(number) -> string Return the hexadecimal representation of an integer or long
integer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With