【问题标题】:Unsigned integer operation questions无符号整数运算题
【发布时间】:2015-06-16 22:53:24
【问题描述】:

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

[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

不知道下面的2个公式能否帮你解决问题:

if (c & 0x1 == 0x1)~c = c OR c-1 //odd colour value), 
if (c & 0x1 == 0x0)~c = c OR c+1 //even colour value.

【问题讨论】:

  • 嗯。在我看来,第二个问题需要“以上都不是”的答案。 (例如,考虑n = 2147483648 在无符号整数为 32 位的系统上的情况。)
  • @MarkDickinson,建议的数字(= 0x80000000)在左移一位时将导致进位为 1,其余数字为 0,即 '2n' 因此答案(e)是正确的

标签: c math binary


【解决方案1】:
  1. (n &amp; ~1)

    • 这是n AND (not 1)
    • (not 1) 产生数字 1,所有位都被否定,所以 11111....11110b
    • AND 是按位乘法所以 0*?=0 , 1*1=1 ,1*u=u
    • 两个数取二进制形式,每个对应的位相乘
    • 所以在AND 使用这个数字之后,最后一位被清除,其余的都保持原样
    • 所以 (b) 是正确的
  2. (n &lt;&lt; 1)

    • 这是左移 1 位
    • 相当于乘以2^1
    • 1b&lt;&lt;1 = 10b = 2
    • 1b&lt;&lt;2 = 100b = 4
    • 1b&lt;&lt;3 = 1000b = 8
    • 5&lt;&lt;1=101b&lt;&lt;1=1010b=10
    • 类似于十进制数乘以 10
    • 所以答案 (e) 是正确的,除非发生溢出
    • n&lt;&lt;1 有更多位时,您的变量可以存储然后您切断 MSB 位
    • 在某些编译器/平台上,它会使用 Carry,但并非总是如此
    • 所以 32 位的正确答案是 (n&lt;&lt;1)=(2*n) mod (2^32)

【讨论】:

    【解决方案2】:

    你可以试试这个ideone代码,看看结果如何

    using System;
    
    public class Test
    {
        public static void Main()
        {
            UInt32 n;
    
            n = 10245;
    
            Console.WriteLine(String.Format("n & ~1 - n = {0}, result = {1}", n, n & ~1));
            Console.WriteLine(String.Format("n << 1 - n = {0}, result = {1}", n, n << 1));
        }
    }
    

    解释为什么依赖于知道bitwise operators defined 的情况并在binary representation 中打印输入和输出数字是应该解释事情的观点

    【讨论】:

    • 那个代码看起来像'生锈'语言,它绝对不是C。
    • @user3629249 可运行的“计算器”sn-p 在C# 中,但位运算符语义与Kernighan &amp; Ritchie C 中的语义相同。我选择了这种语言(尽管从其他 OP 的问题来看,java 似乎会更好)因为在这里我记得如何说“将一些格式化的字符串打印到打字机”,而无需在标准库帮助中搜索。出于测验目的,包装语言应该是无关紧要的
    猜你喜欢
    • 2010-12-16
    • 2020-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-03
    相关资源
    最近更新 更多