The accepted answer didn't address negative numbers, which I'll cover.In addition to the answers above, you can also just use the bin and hex functions. And in the opposite direction, use binary notation:
>>> bin(37)'0b100101'>>> 0b10010137
But with negative numbers, things get a bit more complicated. The question doesn't specify how you want to handle negative numbers.
Python just adds a negative sign so the result for -37 would be this:
>>> bin(-37)'-0b100101'
In computer/hardware binary data, negative signs don't exist. All we have is 1's and 0's. So if you're reading or producing binary streams of data to be processed by other software/hardware, you need to first know the notation being used.
One notation is sign-magnitude notation, where the first bit represents the negative sign, and the rest is the actual value. In that case, -37 would be 0b1100101
and 37 would be 0b0100101
. This looks like what python produces, but just add a 0 or 1 in front for positive / negative numbers.
More common is Two's complement notation, which seems more complicated and the result is very different from python's string formatting. You can read the details in the link, but with an 8bit signed integer -37 would be 0b11011011
and 37 would be 0b00100101
.
Python has no easy way to produce these binary representations. You can use numpy to turn Two's complement binary values into python integers:
>>> import numpy as np>>> np.int8(0b11011011)-37>>> np.uint8(0b11011011)219>>> np.uint8(0b00100101)37>>> np.int8(0b00100101)37
But I don't know an easy way to do the opposite with builtin functions. The bitstring package can help though.
>>> from bitstring import BitArray>>> arr = BitArray(int=-37, length=8)>>> arr.uint219>>> arr.int-37>>> arr.bin'11011011'>>> BitArray(bin='11011011').int-37>>> BitArray(bin='11011011').uint219