I understand that in C, to generate a random number, we use rand(); My plan is (i) to generate a 32 bit random number in binary, (ii) Extract some specific bits from it for specific purposes.
I have tried using int rando = rand() but this at least shows a decimal representation. Which is fine by me but I need to extract certain bits from it. I tried something like:
unsigned long init32;
init32 = ((double)rand()/RAND_MAX)*0b11111111111111111111111111111111111111; printf(" The number is %lu", init32);
which did not give me a binary representation when printed out.
Like I said, I need to extract some specific bits. For example,
How should I go about generating 32 bit binary number for this purpose and then store the 10 bits for Page Table?
I hope I was clear enough. This is for a research project.
"Binary" and "decimal" are just ways to write a number. So twenty is written 20 in decimal and 10100 in binary (and 14 in hexadecimal), but it's still the number twenty in all cases.
Your printf
line is:
printf(" The number is %lu", init32);
When you wrote %lu
, because it ends in u
you actually asked to print the value as a (positive) decimal number. While with printf
you can't print values in binary directly, you can instead print it as hexadecimal, which is perfectly equivalent:
printf(" The number is %lx", init32); // For example: " The number is 14", which means the number is "10100" in binary
From the hexadecimal it's easy to find the binary of the same number because each hex character directly corresponds to a binary representation (e.g. "A" is "1010" in binary): https://www.bbc.co.uk/bitesize/guides/zp73wmn/revision/1 .
If by "extract specific bits", you mean getting the number corresponding to the bits in your schematic, you could do so with something like this (I didn't test it but this should be good or pretty close):
init32 = /* some value */;
// Basically the part on the left side of the "&" takes the entire init32
// and moves it right by that number of bits. Then to cancel the bits on the
// left that you don't want (such as to put to 0 the bits of the "directory"
// when you want to get the page table), we use bitwise "&" with the part on
// the right.
unsigned long directory = (init32 >> 22) & ((1 << (31 - 22 + 1)) - 1);
unsigned long pagetable = (init32 >> 12) & ((1 << (21 - 12 + 1)) - 1);
unsigned long offset = (init32 >> 0 ) & ((1 << (11 - 0 + 1)) - 1);
If that is confusing to you, check out "C bitwise operators" on Google. You do need to understand how numbers work in binary to see what this does though.