【问题标题】:How do I generate a random 32 bit binary number and manipulate it/ extract certain bits from it using C?如何生成一个随机的 32 位二进制数并使用 C 对其进行操作/从中提取某些位?
【发布时间】:2021-07-12 02:51:38
【问题描述】:

我知道在 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 位?

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

【问题讨论】:

  • int 由 N 位组成。您可以将这些位显示为十进制、十六进制或二进制,但它们都是相同的位。你是如何打印号码的?这似乎是你的问题。
  • @RetiredNinja 我只是打印出一个无符号长。在问题中更新。我明白你在说什么,但我的问题是,我该如何提取和存储一定数量的位,例如页表位?
  • 如果你的 rand 函数给你一个介于 0 和 1 之间的值,那么你需要乘以 MAX_VALUE 得到一个 0 到 (MAX_VALUE -1) 范围内的数字。然后使用 > 或位掩码运算符,如 &、|提取您感兴趣的部分。
  • yourrand & 0xfff 将为您提供前 12 位的值(例如位 0-11)。然后(yourrand >> 12) & 0x3ff 会得到页表值。您对目录值的 10 位执行相同的操作。

标签: c bit-manipulation memory-address


【解决方案1】:

“二进制”和“十进制”只是写数字的方式。所以 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/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 位运算符”。您确实需要了解数字在二进制中是如何工作的,才能看到它的作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-03
    • 1970-01-01
    • 1970-01-01
    • 2017-09-24
    • 2011-09-25
    • 1970-01-01
    相关资源
    最近更新 更多