Hello! I'm trying to generate a random 160bit string which is supposed to be stored in a character array named str[20]. It's obvious that the array holds 20 characters. How can I change the 160bits into 20 characters/numbers? I'm trying to do this in C.. Any help is greatly appreciated as I've ran out of ideas and then helpdesk at my uni won't help me..
160 bits is 20 bytes, so can fit in 20 string characters.
If N is a number containing all your bits in a row, you can write a loop like this:
int i;
for (i=0; i<20; i++) {
str[i] = (char)(N & 0xFF);
N >>= 8;
}
Edit: C indeed has no datatype that can hold all your bits in a row. So you need to split up the loop in several subloops for each variable that contains a part of your bits.
If, on the other hand, you are generating one bit at a time on the fly, the code could look like this (assuming your random function is called "random()" and returns an int that is either 0 or 1)
int i, j, b;
for (i=0; i<20; i++)
{
b = 0;
for (j=0; j<8; j++)
{
b |= (random() & 1);
b <<= 1;
}
str[i] = (char)b;
}
This looks like homwork, so I'll only give you the basics:
Your variable will look like:
char str[20];
Note that this array will hold bytes of data, not necessarily "characters" (letter, numbers and punctuation marks as we typically understand the word character").
Unless the assignement is about writing your own random generator, you may want to use C's runtime pseudo-random generator (in stdlib.h
), and use two of its functions: srand()
and rand()
. srand()
is used to "seed" the generator (either seed with same value to get repeatability, useful during debug, or with a variable number (typically related to the system time) to get truly random numbers. rand()
is used to produce integral random values.
Because rand() produces a value between 0 and RAND_MAX (which is a "big" number), you may need to use modulo to get the right amount. for example
str[0] = char(rand() % 256); // or something like that.
rand() however will not produce a 20 bytes integer, so you'll need to get several rand values and fit them appropriately in the array. The most straight forward may be to call rand 20 times and store 1 byte each time, but it is also ok to store several bytes at once, using pointers into parts of str.
a random printable string. If you don't care if it's printable or not, remove the call to min((int)' '). Note I use a null-terminator to make it a proper c-string, if you don't want this, simply remove the part that makes the last character null (and the part taht prints it -- that'll be looking for a null terminator.)
#include <stdlib.h>
int main()
{
char* str[20];
int i;
for (i = 0; i < 19; i++)
{
char[i] = min((int)' ', rand() % CHAR_MAX);
}
char[19] = '\0';
puts(str);
}