微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何生成一个随机的 32 位二进制数并使用 C 操作它/从中提取某些位?

如何解决如何生成一个随机的 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);

打印出来时没有给我二进制表示。 就像我说的,我需要提取一些特定的位。例如,

enter image description here

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

我希望我说得够清楚了。这是一个研究项目。

解决方法

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

您的 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/guides/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 按位运算符”。您确实需要了解数字在二进制中的工作原理,才能了解它的作用。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。