Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Converting str to binary
#1
Hi,

How can I iterate trough a phrase and convert each word to binary and then sum them? Is there a library/module for the alphabet/characteres?

For instance: mystring = 'My beautiful house'

binout = ' '.join('{0:08b}'.format(ord(x), 'b') for x in mystring)

1st_word = 01001101
...
last_word = 01100101
total_phrase = 1st_word + ... + last_word
TIA
Reply
#2
I am not sure what means summation, may be string concatenation in this case.
Hope the following code helps you:

mystring = 'My beautiful house'

def word2bin(w):
    return '0b' + ''.join('{0:08b}'.format(ord(x), 'b') for x in w)

bin(sum(map(lambda x: int(x, 2), (word2bin(x) for x in mystring.split()))))
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Converting an RGBA image to Grayscale and Binary Joni_Engr 3 4,559 Aug-23-2021, 11:54 AM
Last Post: Pedroski55
  hex file to binary or pcap to binary baran01 1 5,629 Dec-11-2019, 10:19 PM
Last Post: Larz60+
  converting binary b'0x31303032\n' to "1002" string amygdalas 2 2,591 Nov-07-2018, 03:50 AM
Last Post: amygdalas
  Converting Decimal to Binary emerger 1 2,767 Feb-27-2018, 08:06 PM
Last Post: Gribouillis
  Converting an 8-bit binary to decimal WITHOUT the shortcuts EIA 5 6,939 Dec-01-2017, 09:04 AM
Last Post: stranac

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020