Converting a string of 1's and 0's to a byte array

I have a string with a length that is a multiple of 8 that contains only 0's and 1's. I want to convert the string into a byte array suitable for writing to a file. For instance, if I have the string "0010011010011101", I want to get the byte array [0x26, 0x9d], which, when written to file, will give 0x269d as the binary (raw) contents.

How can I do this in Python?

Asked by: Lucas930 | Posted: 28-01-2022

Answer 1

py> data = "0010011010011101"
py> data = [data[8*i:8*(i+1)] for i in range(len(data)/8)]
py> data
['00100110', '10011101']
py> data = [int(i, 2) for i in data]
py> data
[38, 157]
py> data = ''.join(chr(i) for i in data)
py> data

Answered by: Melissa219 | Posted: 01-03-2022

Answer 2

You could do something like this:

>>> s = "0010011010011101"
>>> [int(s[x:x+8], 2) for x in range(0, len(s), 8)]
[38, 157]

Answered by: Cadie865 | Posted: 01-03-2022

Answer 3

Your question shows a sequence of integers, but says "array of bytes" and also says "when written to file, will give 0x269d as the binary (raw) contents". These are three very different things. I think you've over-specified. From your various comments it looks like you only want the file output, and the other descriptions were not what you wanted.

If you want a sequence of integers, look at Greg Hewgill's answer.

If you want a sequence of bytes (as in a string) -- which can be written to a file -- look at Martin v. Löwis answer.

If you wanted an array of bytes, you have to do this.

import array
intList= [int(s[x:x+8], 2) for x in range(0, len(s), 8)]
byteArray= array.array('B', intList)

Answered by: Chelsea290 | Posted: 01-03-2022

Answer 4

Python 3 and number.to_bytes

With Python 3 you can convert numbers to bytes natively with number.to_bytes. The byte array can be written directly to a file.

>>> import math,sys
>>> s='0010011010011101'
>>> int(s,2).to_bytes(math.ceil(len(s)/8),sys.byteorder)
>>> with open('/tmp/blah', 'wb') as f:
...     f.write(int(s,2).to_bytes(math.ceil(len(s)/8),sys.byteorder))
>>> quit()

file contents

[root@localhost prbs]# od -x /tmp/blah
0000000 269d

Answered by: Ted651 | Posted: 01-03-2022

Similar questions

python - Converting a list to a string

This question already has answers here:

python - Converting string to tuple and adding to tuple

I have a config file like this. [rects] rect1=(2,2,10,10) rect2=(12,8,2,10) I need to loop through the values and convert them to tuples. I then need to make a tuple of the tuples like ((2,2,10,10), (12,8,2,10))

python - converting string to list

How to convert string to list str = '[(, amit, laspal,1,100,50), (,None,None,None,None,None), (,laspal, amit,None,None,None)]' I want to get tuple inside the list. so my new list will be: list =[(, amit, laspal,1,100,50), (,None,None,None,None,None),...

python - Converting String to List

This question already has answers here:

python - Converting string to ascii using ord()

I must preface this by saying that I am a neophyte (learning), so please waive the omission of the obvious in deference to a man who has had limited exposure to your world (Python). My objective is to get string from a user and convert it to Hex and Ascii string. I was able to accomplish this successfully with hex (encode("hex")), but not so with ascii. I found the ord() method and attempt...

python - Converting a String to a List of Words?

I'm trying to convert a string to a list of words using python. I want to take something like the following: string = 'This is a string, with words!' Then convert to something like this : list = ['This', 'is', 'a', 'string', 'with', 'words'] Notice the omission of punctuation and spaces. What would be the fastest way of going about this?

python converting string to int and adding 1

python - converting a string to a list of tuples

I need to convert a string, '(2,3,4),(1,6,7)' into a list of tuples [(2,3,4),(1,6,7)] in Python. I was thinking to split up at every ',' and then use a for loop and append each tuple to an empty list. But I am not quite sure how to do it. A hint, anyone?

Python 3: Converting A Tuple To A String

I have the following code: var_one = var_two[var_three-1] var_one = "string_one" + var_1 And I need to do the following to it: var_four = 'string_two', var_one However, this returns the following error: TypeError: Can't convert 'tuple' object to str implicity I have tried things such as str(var_one) and using ...

python - Converting string to int is too slow

I've got a program that reads in 3 strings per line for 50000. It then does other things. The part that reads the file and converts to integers is taking 80% of the total running time. My code snippet is below: import time file = open ('E:/temp/edges_big.txt').readlines() start_time = time.time() for line in file[1:]: label1, label2, edge = line.strip().split() # label1 = int(label1); label...

Python converting from tuple to string

I know for many of you that would be easy thing to do, but for me no. So I'm trying to output data from shell, but I'm stucked when I have to transform it into string. I tried with for, but didn't work. So basically, what I'm trying is: for each new line in my shell, output new line. I'll give an example - the free -m command. Its output is total used free shared ...

python - Converting a string to floats error

So I am trying to run this piece of code: reader = list(csv.reader(open('mynew.csv', 'rb'), delimiter='\t')) print reader[1] number = [float(s) for s in reader[1]] inside reader[1] i have the following values: '5/1/2013 21:39:00.230', '46.09', '24.76', '0.70', '0.53', '27.92', I am trying to store each one of values into an array like so: n...

python - Converting string taken from URL into list

I'm trying to take the string I'm receiving from a website using 'getHTML' and turn it into a list of all of the words in the string, but my code doesn't seem to be cooperating. What am I doing wrong? from hmc_urllib import getHTML def TextClouds(): url = input('HTML, please:') x = getHTML(url) return x.split()

python - Converting list to string?

This question already has answers here:

python - Converting to sql style string

This question already has answers here:

python - Converting a list to string with prefix and suffix

I have this list: myist = ['0', '1', '2', '3'] and I want to execute something via os.system() where multiple files are used in one line: cat file0.txt file1.txt file2.txt file3.txt > result.txt but I'm not sure how to add a suffix when joining the list. This: os.system("cat file" + ' file'.join(mylist) +".txt > result.txt" )

python - Converting string to number?

This question already has an answer here:

python - Converting string file into json format file

Ok , let say that I have a string text file named "string.txt" , and I want to convert it into a json text file. What I suppose to do? I have tried to use 'json.loads()' ,but it never works with me! here is a part from my text file : rdian","id":"161428670566653"},{"category":"Retail and consumer merchandise","category_list":[{"id":"187937741228885","name":"Electronics Store"},{"id":"191969860827280","name"...

python - Error converting list to string

I am trying to specify the position where I would like my data to be written in my output file but I am getting the following error. Could I please be advised on how I might resolve this issue? Traceback (most recent call last): File "C:/Python33/Upstream and downstream", line 20, in <module> upstream_shore.writerow (line[0] + [upstream_1] + line[1]) TypeError: Can't convert 'list' obj...

python - Converting string to date object without time info

I'd like to convert a string to a Python date-object. I'm using d = datetime.strptime("25-01-1973", "%d-%m-%Y"), as per the documentation on, and that yields datetime.datetime(1973, 1, 25, 0, 0). When I use d.isoformat(), I get '1973-01-25T00:00...

Converting PDF to HTML with Python

This question already has answers here:

Is there a Python module for converting RTF to plain text?

Closed. This question does not meet Stack Overflow guid...

Converting Python code to PHP

What is the following Python code in PHP? import sys li = range(1,777); def countFigure(li, n): m = str(n); return str(li).count(m); # counting figures for substr in range(1,10): print substr, " ", countFigure(li, substr); Wanted output for 777 1 258 2 258 3 258 4 258 5 258 6 258 7 231 8 147 9 147

Help in Converting Small Python Code to PHP

please i need some help in converting a python code to a php syntax the code is for generating an alphanumeric code using alpha encoding the code : def mkcpl(x): x = ord(x) set="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" for c in set: d = ord(c)^x if chr(d) in set: return 0,c,chr(d) if chr(0xff^d) in set: ...

python - Converting \n to <br> in mako files

I'm using python with pylons I want to display the saved data from a textarea in a mako file with new lines formatted correctly for display Is this the best way of doing it? &gt; ${['about_me'].replace("\n", "&lt;br /&gt;") | n}

utf 8 - Converting from ascii to utf-8 with Python

I have xmpp bot written in python. One of it's plugins is able to execute OS commands and send output to the user. As far as I know output should be unicode-like to send it over xmpp protocol. So I tried to handle it this way: output = os.popen(cmd).read() if not isinstance(output, unicode): output = unicode(output,'utf-8','ignore') bot.send(xmpp.Message(mess.getFrom(),output)) But whe...

python - Converting a list to a string

This question already has answers here:

python - Error Converting PIL B&W images to Numpy Arrays

I am getting weird errors when I try to convert a black and white PIL image to a numpy array. An example of the code I am working with is below. if image.mode != '1': image = image.convert('1') #convert to B&amp;W data = np.array(image) #Have also tried np.asarray(image) n_lines = data.shape[0] #number of raster passes line_range = range(data.shape[1]) for l in range(n_lines): ...

python - Converting videos for iPhone - ffmpeg

Closed. This question is off-topic. It is not curre...

python - Help converting .py to .exe, using py2exe

The script I ran # # very simple script to make an executable file with py2exe # put this script and your code script into the same folder # run # it will create a subfolder 'dist' where your exe file is in # has the same name as the script_file with extension exe # (the other subfolder 'build' can be deleted) # note: with console code put a wait line at the end from dis...

python - Converting datetime to POSIX time

How do I convert a datetime or date object into a POSIX timestamp in python? There are methods to create a datetime object out of a timestamp, but I don't seem to find any obvious ways to do the operation the opposite way.

Converting PDF to HTML with Python

This question already has answers here:

python - Library for converting a traceback to its exception?

Just a curiosity: is there an already-coded way to convert a printed traceback back to the exception that generated it? :) Or to a sys.exc_info-like structure?

vb6 - Is there a tool for converting VB to a scripting language, e.g. Python or Ruby?

I've discovered VB2Py, but it's been silent for almost 5 years. Are there any other tools out there which could be used to convert VB6 projects to Python, Ruby, Tcl, whatever?

python - Converting from mod_python to mod_wsgi

My website is written in Python and currently runs under mod_python with Apache. Lately I've had to put in a few ugly hacks that make me think it might be worth converting the site to mod_wsgi. But I've gotten used to using some of mod_python's utility classes, especially FieldStorage and Session (and sometimes Cookie), and from a scan of

django - Converting to safe unicode in python

I'm dealing with unknown data and trying to insert into a MySQL database using Python/Django. I'm getting some errors that I don't quite understand and am looking for some help. Here is the error. Incorrect string value: '\xEF\xBF\xBDs m...' My guess is that the string is not being properly converted to unicode? Here is my code for unicode conversion. s = unicode(content...

Oracle / Python Converting to string -> HEX (for RAW column) -> varchar2

I have a table with a RAW column for holding an encrypted string. I have the PL/SQL code for encrypting from plain text into this field. I wish to create a trigger containg the encryption code. I wish to 'misuse' the RAW field to pass the plain text into the trigger. (I can't modify the schema, for example to add another column for the plain text field) The client inserting the data is Pytho...

python - How can I check Hamming Weight without converting to binary?

How can I get the number of "1"s in the binary representation of a number without actually converting and counting ? e.g. def number_of_ones(n): # do something # I want to MAKE this FASTER (computationally less complex). c = 0 while n: c += n%2 n /= 2 return c &gt;&gt;&gt; number_of_ones(5) 2 &gt;&gt;&gt; number_of_ones(4) 1 ...

python - Django: Converting an entire set of a Model's objects into a single dictionary

If you came here from Google looking for model to dict, skip my question, and just jump down to the first answer. My question will only confuse you. Is there a good way in Django to entire set of a Model's objects into a single dictionary? I mean, like this: class DictModel(models.Model): key = models.CharField(20) value = models.CharField(200) DictModel.objects.all().to_dict()

python - What is the difference between converting to hex on the client end and using rawtohex?

I have a table that's created like this: CREATE TABLE bin_test (id INTEGER PRIMARY KEY, b BLOB) Using Python and cx_Oracle, if I do this: value = "\xff\x00\xff\x00" #The string represented in hex by ff00ff00 self.connection.execute("INSERT INTO bin_test (b) VALUES (rawtohex(?))", (value,)) self.connection.execute("SELECT b FROM bin_test")

Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python