0

So what the function does is ask for input for the file name, k-bit binary strings, and n number of times to write k-bit binary strings.

def makeStrings():
    fileName = str(input("File Name: "))
    k = input("Bits Input: ")
    n = int(input("Number of Strings: "))
    outputFile = open(fileName, "w")
    counter = 0
    while (counter < n):
        randomNumber = random.randint(0, 9223372036854775808) #that big number is the max representation of a 64bit binary string
        binary = ('{:0' + str(k) + 'b}').format(randomNumber)
        outputFile.write(str(binary) + "\n")
        counter = counter + 1
    outputFile.close()   

So what my issue is is that the function works. It does what it is suppose to do except that it doesn't format the binary to be k-bits long. so say for instance I could have any binary representation from random numbers, but I only want them to be k-bits long. so if I make k = 8 it should give me random 8-bit binary strings that are 8 bits long or if I make k = 15 it should give me random 15-bit binary strings.

So say for instance my input is

>>> FileName: binarystext.txt #Name of the file
>>> 16 #number of bits for binary string
>>> 2 #number of times the k-bit binary string is written to the file

It should write to the file the following

1111110110101010
0001000101110100

the same representation would be applied for any bit binary string. 2, 3, 8, 32 etc.

I thought of maybe splitting all the numbers into their represented binary forms so like 0-255 for 8 bit for example and I would just format it if k = 8, but that would mean I would have to do that a ton of times.

Right now what I get is

1010001100000111111001100010000001000000011010111

or some other really long binary string.

2 Answers 2

1

The problem is that width in format string is the minimum width of the field:

width is a decimal integer defining the minimum field width. If not specified, then the field width will be determined by the content.

You could just limit the number you're randomizing to fix the issue:

randomNumber = random.randint(0, 2 ** k - 1)
Sign up to request clarification or add additional context in comments.

Comments

0

Use random.getrandbits() and a format string:

>>> import random
>>> random.getrandbits(8)
41
>>> 
>>> s = '{{:0{}b}}'
>>> k = 24
>>> s = s.format(k)
>>> s.format(random.getrandbits(k))
'101111111001101111100100'
>>> 

1 Comment

You need to specify prefix and width in the format string in case that first bit(s) are 0. The second example you provided contains only 20 characters although you randomized 24 bits.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.