3 Replies - 5689 Views - Last Post: 14 August 2011 - 11:27 AM Rate Topic: -----

#1 ABC111111  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • 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.
Any advice or tips would be greatly appreciated. Thanks in advance!
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  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 452
  • View blog
  • Posts: 796
  • 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))


Was This Post Helpful? 0
  • +
  • -

#3 ABC111111  Icon User is offline

  • New D.I.C Head

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

Re: Convert string to 8-bit binary

Posted 13 August 2011 - 08:59 AM

View PostMotoma, 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.
Was This Post Helpful? 0
  • +
  • -

#4 Motoma  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 452
  • View blog
  • Posts: 796
  • Joined: 08-June 10

Re: Convert string to 8-bit binary

Posted 14 August 2011 - 11:27 AM

What version are you using?
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1