C 无符号整数运算问题

C 无符号整数运算问题,c,math,binary,C,Math,Binary,这些不是作业也不是家庭作业。 我正在准备中考。我需要有人告诉我哪个是正确的答案,并向我详细解释原因 [2 marks] Given an unsigned integer n, the operation (n & ~1) will produce (a) the value n mod 4 (b) n with its least significant bit cleared (i.e. set to 0) (c) the value 2n (d) the value n/2 (e)

这些不是作业也不是家庭作业。 我正在准备中考。我需要有人告诉我哪个是正确的答案,并向我详细解释原因

[2 marks] Given an unsigned integer n, the operation (n & ~1) will produce
(a) the value n mod 4
(b) n with its least significant bit cleared (i.e. set to 0)
(c) the value 2n
(d) the value n/2
(e) the least significant bit of n

[1 mark] Given an unsigned integer n, the operation (n << 1) will produce
(a) n with its least significant bit cleared (i.e. set to 0)
(b) the value n mod 4
(c) the value n/2
(d) the least significant bit of n
(e) the value 2n
您可以试试这段代码,看看结果如何

使用系统;
公开课考试
{
公共静态void Main()
{
UInt32-n;
n=10245;
WriteLine(String.Format(“n&~1-n={0},result={1}”,n,n&~1));
Console.WriteLine(String.Format(“n
  • (n&~1)

    • 这是
      n和(不是1)
    • (不是1)
      生成所有位均为负数的数字1,因此
      11111…11110b
    • 是位乘法,因此
      0*?=0
      1*1=1
      1*u=u
    • 两个数字采用二进制形式,每个对应位相乘
    • 因此,在
      使用此数字后,最后一位被清除,其余的都保持原样
    • 所以(b)是正确的

  • Hmm.认为我的第二个问题需要一个“以上没有”的答案。(例如,在一个无符号整数为32位的系统中考虑案例<代码> n=2147483648 < /代码>)左移一位将导致进位为1,其余数字为0,即“2n”,因此答案(e)正确代码看起来像“rust”语言,它肯定不是C。@user3629249“可运行”计算器“snippet在
    C#
    中,但按位运算符语义与
    Kernighan&Ritchie C
    中的相同。我选择了这种语言(尽管从其他OP的问题来看,
    java
    似乎更好),因为我记得在这里如何说“将一些格式化字符串打印到打字机上”无需在标准库帮助中搜索。对于测验目的,包装语言应该是无关的
    if (c & 0x1 == 0x1)~c = c OR c-1 //odd colour value), 
    if (c & 0x1 == 0x0)~c = c OR c+1 //even colour value.