tags:

views:

39

answers:

4

As I understand it, files like /dev/urandom provide just a constant stream of bits. The terminal emulator then tries to interpret them as strings, which results in a mess of unrecognised characters.

How would I go about doing the same thing in python, send a string of ones and zeros to the terminal as "raw bits"?

edit I may have to clarify: Say for example the string I want to "print" is 1011100. On an ascii system, the output should be "\". If I cat /dev/urandom, it provides a constant stream of bits. Which get printed like this: "���c�g/�t]+__��-�;". That's what I want.

A: 
import sys, random
while True:
    sys.stdout.write(chr(random.getrandbits(8)))
    sys.stdout.flush()
Chris B.
I may have phrased it poorly.The output stream of the program should not be a string containing ones and zeros, but rather ones and zeros in their pure form, such as the ones a string would consist of. The number 1 is represented in ascii as 49, or 011 0001. The program should not send binary 49 to the terminal, but my stream of ones and zeros instead. If there happens to be the sequence 011 0001 in the stream, the terminal is going to interpret this as the ascii letter "1". I hope this explains what I'm on about.
stefano palazzo
Then edit your question.
Chris B.
@Chris: the question is quite unanbiguous. I wonder how one could interpreted "a mess of unrecognised characters" as chars "0" and "1".
jsbueno
"A string of ones and zeros" means a string composed of ones and zeros. That's pretty unambiguous, IMHO.
Chris B.
It happens it is ambiguous in this context, as the "ones and zeros" meant where bit values, not char values (neither bytes). The uninanbiguous phrase was the one I pointed out.
jsbueno
A: 

And from another question on StackOverflow you can get a _bin function.

def _bin(x, width):
    return ''.join(str((x>>i)&1) for i in xrange(width-1,-1,-1))

Then simply put call _bin(ord(x), 8) where x is a character (string of length one)

Umang
This does not answer the question..it outputs a strign with '0' and '1' chars instead.
jsbueno
Uh oh. I didn't read carefully, did it?
Umang
A: 

Use the chr function. I takes an input between 0 and 255 and returns a string containing the character corresponding to that value.

You
+1  A: 

Stephano: the key is the incomplete answer by "@you" above - the chr function :

import random, sys

for i in xrange(500):
   sys.stdout.write(chr(random.randrange(256)))
jsbueno
Thank you, this was exactly what I was looking for.
stefano palazzo