Is there an easy way to get some str/unicode object represented as a big binary number (or an hex one)?
I've been reading some answers to related questions but none of them works for my scenario.
I tried using the struct module from the STL but it didn't work as expected. Chars, like in binary files are displayed as, well chars.
Am I trying something impossible?
Example:
def strbin(inp):
# sorcery!
return out
>> print strbin("hello")
# Any of these is cool (outputs are random keystrokes)
0b1001010101010000111001110001...
0xad9f...
You could try bitarray
:
>>> import bitarray
>>> b = bitarray.bitarray()
>>> b.fromstring('a')
>>> b
bitarray('01100001')
>>> b.to01()
'01100001'
>>> b.fromstring('pples')
>>> b.tostring()
'apples'
>>> b.to01()
'011000010111000001110000011011000110010101110011'
This is basically Ravi's answer but with a tiny bugfix, so all credit to him, but the consensus among reviewers was that this was too big of a change to just do an edit and should be a separate answer instead... No idea why.
def strhex(str):
h=""
for x in str:
h=h+("0" + (hex(ord(x)))[2:])[-2:]
return "0x"+h
The difference is that in line 4, you have to check if the character is less than 0x10 and in that case prepend a zero, otherwise e.g. 0x1101 becomes 0x111.
Quite simple and don't require modules from pypi:
def strbin(s):
return ''.join(format(ord(i),'0>8b') for i in s)
You'll need Python 2.6+ to use that.
def strhex(str):
h=""
for x in str:
h=h+(hex(ord(x)))[2:]
return "0x"+h
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