6

I know this is easily possible in python 2.6. But what is the easiest way to do this in Python 2.5?

x = "This is my string"
b = to_bytes(x)  # I could do this easily in 2.7 using bin/ord 3+ could use b"my string"
print b

Any suggestions? I want to take the x and turn it into

00100010010101000110100001101001011100110010000001101001011100110010000001101101011110010010000001110011011101000111001001101001011011100110011100100010

5
  • 1
    Is your 'xml string' really a str() and not a unicode() object? Commented Dec 18, 2011 at 18:34
  • Its an str(). Formed almost exactly as above, I could make it unicode.. Commented Dec 18, 2011 at 20:18
  • Actually, byte literal notation is in 2.6+. Commented Dec 19, 2011 at 2:30
  • try echo -n 'This is my string' | xxd -b Commented Jan 10, 2012 at 15:42
  • related: Convert Binary to ASCII and vice versa Commented Mar 12, 2014 at 11:00

2 Answers 2

7

This one-line works:

>>> ''.join(['%08d'%int(bin(ord(i))[2:]) for i in 'This is my string'])
'0101010001101000011010010111001100100000011010010111001100100000011011010111100100100000011100110111010001110010011010010110111001100111'

EDIT

You can write bin() yourself

def bin(x):
    if x==0:
        return '0'
    else:
        return (bin(x/2)+str(x%2)).lstrip('0') or '0'
Sign up to request clarification or add additional context in comments.

1 Comment

@Nix You can write bin() yourself
1

I think you could do it in a cleaner way like this:

>>>''.join(format(ord(c), '08b') for c in 'This is my string')
'0101010001101000011010010111001100100000011010010111001100100000011011010111100100100000011100110111010001110010011010010110111001100111'

the format function will represent the character in a 8 digits, binary representation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.