gpt4 book ai didi

c - k&r练习2-6 "setbits"

转载 作者:太空宇宙 更新时间:2023-11-04 08:13:05 26 4
gpt4 key购买 nike

我在这里看到了答案:http://clc-wiki.net/wiki/K%26R2_solutions:Chapter_2:Exercise_6

我已经测试了第一个,但在这部分:

x = 29638;
y = 999;
p = 10;
n = 8;

return (x & ((~0 << (p + 1)) | (~(~0 << (p + 1 - n)))))

在一篇论文中它给我一个 6,但在程序中它返回 28678...

这部分:

 111001111000110
&000100000000111

在结果中,最左边的三位必须像 x 中那样为 1,但按位运算符 & 表示:

The output of bitwise AND is 1 if the corresponding bits of all operands is 1. If either bit of an operand is 0, the result of corresponding bit is evaluated to 0.

那么为什么它返回的是 3 位合 1 的数字呢?

最佳答案

我们开始吧,一次一个步骤(使用 16 位数字)。我们从:

(x & ((~0 << (p + 1)) | (~(~0 << (p + 1 - n)))))

代入数字(十进制):

(29638 & ((~0 << (10 + 1)) | (~(~0 << (10 + 1 - 8)))))

总计位移量给出:

(29638 & ((~0 << 11) | (~(~0 << 3))))

将数字重写为二进制并应用~0...

(0111001111000110 & ((1111111111111111 << 1011) | (~(1111111111111111 << 0011))))

执行轮类后我们得到:

(0111001111000110 & (1111100000000000 | (~ 1111111111111000)))

应用另一个按位非(~):

(0111001111000110 & (1111100000000000 | 0000000000000111))

和按位或(|):

0111001111000110 & 1111100000000111

最后是按位与 (&):

0111000000000110

因此我们有二进制 0111000000000110,即 2 + 4 + 4096 + 8192 + 16384,即 28678

关于c - k&r练习2-6 "setbits",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37738387/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com