0

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.

Stefano Palazzo
  • 4,212
  • 2
  • 29
  • 40
  • `while True: print '���c�g/�t]+__��-�'` as any garbage is as good as any other ;) Why do you want to do this? There are "the matrix movie" screensavers that look cooler. – msw Jul 10 '10 at 15:05
  • A string is not a stream is not a binary number. You're using the terms interchangeably, which is very confusing. – Chris B. Jul 10 '10 at 15:10

4 Answers4

3

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
  • 99,910
  • 10
  • 151
  • 209
1

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

You
  • 22,800
  • 3
  • 51
  • 64
0
import sys, random
while True:
    sys.stdout.write(chr(random.getrandbits(8)))
    sys.stdout.flush()
Chris B.
  • 85,731
  • 25
  • 98
  • 139
  • 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 Jul 10 '10 at 14:51
  • the question is quite unanbiguous. I wonder how one could interpreted "a mess of unrecognised characters" as chars "0" and "1". – jsbueno Jul 10 '10 at 15:02
  • "A string of ones and zeros" means a string composed of ones and zeros. That's pretty unambiguous, IMHO. – Chris B. Jul 10 '10 at 15:06
  • 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 Jul 10 '10 at 16:00
0

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)

Community
  • 1
  • 1
Umang
  • 5,196
  • 2
  • 25
  • 24