codingdir logo sitemap sitemap |
Home
PHP
C#
C++
ANDROID
JAVA
JAVASCRIPT
PYTHON

Write a binary integer or string to a file in python


By : , Category : python

This would write your string to a file:

with open('myfile', 'w') as fobj:
    fobj.write("001011010110000010010")
ReLated :

I found answer for this question in using another encoding, and writing bytes:

file = open('file.bin','wb')
cur = 0
while cur < len(code):
    c = int(code[cur:cur+8], 2)
    file.write(bytes(chr(c), 'iso8859-1'))
    cur += 8

I wrote string with 0 and 1: 000101101100000000010010110000010011000000010010001000100000000000010111110000110100001100010001

And if i open file with notepad I will see АБ0" ГC some symbols not shown... but if i will open file in hex redactor I will see:

00010110 11000000 00010010 11000001 00110000 00010010 00100010 00000000 00010111 11000011 01000011 00010001

Best 96 bits!

It seems you need struct:

import struct
import numpy as np # for random string of ones and zeros

def chunks(s):
    for i in xrange(0, len(s), 32):
         yield s[i:i+32]

s =  ''.join(str(np.random.randint(2)) for x in xrange(32*2))
ints = (int(x, 2) for x in chunks(s)) # convert string from binary repr to integers
bins = (struct.pack('I', i) for i in ints) # pack to unsigned ints

output:

>>> s
'0000000000011111011101011001010111000000010110111100111110001001'
>>> ''.join(bins)
'x95ux1fx00x89xcf[xc0'

Note that I format is unsigned int in native format, you can specify byte order expicetely, with >I being big-endian int32, and <I little-endian (note reversed order of 4-byte sequences):

>>> bi_bins = (struct.pack('>I',  i) for i in ints)
>>> ''.join(bi_bins)
'x00x1fux95xc0[xcfx89'

As @Ben just said, use fwrite. Supposing your uint32 variable is stored in A which is of type uint32, and supposing you want to write to a file called test.txt, simply do this:

fid = fopen('test.txt', 'w'); %// Open test.txt for writing
fwrite(fid, A, 'uint32'); %// Write this single uint32 number to file
fclose(fid); %// Close the file to register the changes

Try using string format method:

write("{0}%".format(grades[1]))
Comments


Message :
Login to Add Your Comments .
How to disable registered OpenCL platforms on Windows?
Is Observable broken in Angular 2 Beta 3?
Cross-thread operation not valid when using Invoke
How to pass an IEnumerable or queryable list of properties from Controller to View
Finding numbers after a certain keyword using Python
Pocketsphinx recognizes random phrases in a silence
Passing non-thread-safe objects through thread-safe containers
React scroll nav
BizTalk WCF-BasicHttp Adapter does not allow Empty string for Service Certificate Props
Why property ''cause" of Exception is repeating forever?
Privacy Policy 2017 © codingdir.com All Rights Reserved .