首页 > 解决方案 > 如何生成一个随机的 32 位二进制数并使用 C 对其进行操作/从中提取某些位?

问题描述

我知道在 C 中,要生成随机数,我们使用 rand(); 我的计划是(i)生成一个 32 位二进制随机数,(ii)从中提取一些特定位用于特定目的。

我尝试过使用 int rando = rand() 但这至少显示了十进制表示。这对我来说很好,但我需要从中提取某些位。我试过类似的东西: unsigned long init32; init32 = ((double)rand()/RAND_MAX)*0b11111111111111111111111111111111111111; printf(" The number is %lu", init32);

打印出来时没有给我二进制表示。就像我说的,我需要提取一些特定的位。例如, 在此处输入图像描述

我应该如何为此目的生成 32 位二进制数,然后为页表存储 10 位?

我希望我足够清楚。这是一个研究项目。

标签: cbit-manipulationmemory-address

解决方案


“二进制”和“十进制”只是写数字的方式。所以 20 用十进制写成 20,用二进制写成 10100(十六进制写成 14),但在所有情况下它仍然是数字 20。

您的printf线路是:

printf(" The number is %lu", init32);

当您写 时%lu,因为它以u您实际要求将值打印为(正)十进制数而结束。虽然printf您不能直接以二进制打印值,但您可以将其打印为十六进制,这完全等效:

printf(" The number is %lx", init32); // For example: " The number is 14", which means the number is "10100" in binary

从十六进制很容易找到相同数字的二进制,因为每个十六进制字符直接对应于二进制表示(例如“A”在二进制中是“1010”):https ://www.bbc.co.uk/bitesize/指南/zp73wmn/revision/1

如果通过“提取特定位”,您的意思是获取与原理图中的位相对应的数字,您可以这样做(我没有测试它,但这应该很好或非常接近):

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);

如果这让您感到困惑,请查看 Google 上的“C 位运算符”。您确实需要了解数字在二进制中是如何工作的,以了解它的作用。


推荐阅读