# Convert string to 8-bit binary

Page 1 of 1

## 3 Replies - 10944 Views - Last Post: 14 August 2011 - 11:27 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=243324&amp;s=d21aef831f0ebd7235650276966ee79d&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 ABC111111

Reputation: 0
• Posts: 7
• Joined: 18-July 11

# Convert string to 8-bit binary

Posted 12 August 2011 - 02:22 PM

This is what I have so far. I can take the string and convert each character into an integer, and create a list of the integers. Converting each integer into a hypothetical list such as [1,0,0,1,1,0,1,1] is where I'm stuck.
p.s I am trying to work in base 2.

def string_to_bits(string):
'''Return the list of bits that represents the input string.'''
one_string = string.replace(" ", "")
char_list = list(one_string)

new_list = []

for i in char_list:
num = ord(i)
new_list.append(num)
return new_list

This post has been edited by ABC111111: 12 August 2011 - 02:24 PM

Is This A Good Question/Topic? 0

## Replies To: Convert string to 8-bit binary

### #2 Motoma

Reputation: 452
• Posts: 798
• Joined: 08-June 10

## Re: Convert string to 8-bit binary

Posted 12 August 2011 - 04:35 PM

You can utilize the struct.unpack() function to convert your string into integer numbers, and the bin() function to then convert each integer into binary:

```from struct import unpack
s = b"Hello, world"
t = unpack('b' * len(s), s)
for i in t:
print(bin(t))

```

### #3 ABC111111

Reputation: 0
• Posts: 7
• Joined: 18-July 11

## Re: Convert string to 8-bit binary

Posted 13 August 2011 - 08:59 AM

Motoma, on 12 August 2011 - 04:35 PM, said:

You can utilize the struct.unpack() function to convert your string into integer numbers, and the bin() function to then convert each integer into binary:

```from struct import unpack
s = b"Hello, world"
t = unpack('b' * len(s), s)
for i in t:
print(bin(t))

```

Thank you for your reply, but the version of python I'm using doesn't allow me to use the bin() function.

### #4 Motoma

Reputation: 452
• Posts: 798
• Joined: 08-June 10

## Re: Convert string to 8-bit binary

Posted 14 August 2011 - 11:27 AM

What version are you using?