Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Python str/unicode object to binary/hex blob

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...
like image 977
toqueteos Avatar asked Jul 18 '11 02:07

toqueteos


4 Answers

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'
like image 97
senderle Avatar answered Sep 23 '22 02:09

senderle


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.

like image 23
FrederikVds Avatar answered Sep 27 '22 02:09

FrederikVds


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.

like image 43
JBernardo Avatar answered Sep 23 '22 02:09

JBernardo


def strhex(str):
    h=""
    for x in str:
        h=h+(hex(ord(x)))[2:]
    return "0x"+h
like image 31
Ravi Avatar answered Sep 27 '22 02:09

Ravi