c - 家庭作业 - C 位谜题 - 使用 C 位操作执行 %(无循环、条件、函数调用等)

标签 c bit-manipulation

我完全被困在如何做这个家庭作业问题上,正在寻找一两个提示来让我继续前进。我被限制为 20 次操作(= 不算在这 20 次中)。

我应该填写一个如下所示的函数:

    /* Supposed to do x%(2^n).
       For example: for x = 15 and n = 2, the result would be 3.

       Additionally, if positive overflow occurs, the result should be the
       maximum positive number, and if negative overflow occurs, the result
       should be the most negative number.
     */
    int remainder_power_of_2(int x, int n){

      int twoToN = 1 << n;

      /* Magic...? How can I do this without looping? We are assuming it is a
         32 bit machine, and we can't use constants bigger than 8 bits
         (0xFF is valid for example).
         However, I can make a 32 bit number by ORing together a bunch of stuff.
         Valid operations are: << >> + ~ ! | & ^
       */

      return theAnswer;
    }

我在想也许我可以将 twoToN 移到左边...直到我以某种方式检查(没有 if/else)它大于 x,然后再移回右边一次。 .. 然后用 x... 异或它并重复?但是我只有 20 个操作!

最佳答案

提示:在十进制系统中以 10 的次方取模,您只需保留最后几位数字并将其他数字清零。例如。 12345 % 100 = 00045 = 45。嗯,在计算机中数字是二进制的。所以你必须使二进制数字(位)为空。因此,请查看各种位操作运算符(&|^)来执行此操作。

关于c - 家庭作业 - C 位谜题 - 使用 C 位操作执行 %(无循环、条件、函数调用等),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12148246/

相关文章:

c - 各个函数的内存分配?

中断可以中断自身吗?

Java Long - 位的操作

java - 使用枚举/按位将 DaysOfWeek 作为单个整数存储在 sqlite 数据库中 - Java

c - 套接字:处理 APUE 书中的示例

使用 pthreads 在 C 中将顺序循环转换为并行循环

c - 我的 C 宏做错了什么?

c - 在 int 的每个半字节中切换位

c - 解压 16 位 BCD 的最有效公式? (例如 0x1234 到 0x01020304)

c - 将有符号整数除以 2 的幂