Generating Random text file of size x bits

4 views (last 30 days)
Geboz Rent
Geboz Rent on 9 Feb 2015
Answered: Ayush on 21 Oct 2024
I would like to create a txt of strings/numbers that is of size x bits given the value of x
say if x = 245760 bits
This is to embed an image with x bits message.

Answers (1)

Ayush
Ayush on 21 Oct 2024
Hi,
To generate a random text file of a specified size in bits, you first need to convert the size from bits to bytes, as file sizes are typically measured in bytes. Since 1 byte equals 8 bits, a file size of 245,760 bits translates to 30,720 bytes (245,760 bits / 8 bits per byte). You can generate random alphanumeric characters, with each character typically occupying 1 byte. By writing these characters to a text file, you can achieve the desired file size.
Refer to the example code below:
% Desired file size in bits
x_bits = 245760;
% Convert bits to bytes
x_bytes = x_bits / 8;
% Generate random alphanumeric characters
% Use ASCII range for alphanumeric characters: 48-57 (0-9), 65-90 (A-Z), 97-122 (a-z)
characters = ['0':'9' 'A':'Z' 'a':'z'];
num_chars = length(characters);
% Generate a random string of the required length
random_string = characters(randi(num_chars, 1, x_bytes));
% Write to a text file
fileID = fopen('random_text.txt', 'w');
fwrite(fileID, random_string);
fclose(fileID);

Categories

Find more on Convert Image Type in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!