本文介绍了了解移位运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白这种转变运算符(C#参考):

 类MainClass1 
{
静态无效的主要()
{
INT I = 1;
长LG = 1;
Console.WriteLine(0X {0:X},I<< 1);
Console.WriteLine(0X {0:X},I<< 33);
Console.WriteLine(0X {0:X},LG&所述;γ-33);
}
}

/ *
输出:
0X2
0X2
0x200000000
* /

类MainClass2
{
静态无效的主要()
{
int类型的= 1000;
A&所述;&下; = 4;
Console.WriteLine(一);
}
}

/ *
输出:
16000
* /


解决方案

<< 是左移位运算符;这需要一个值的二进制表示,并且所有的位的n位置向左移动(除了MOD,见1),用零回填



>> 是右移位运算符;这样做几乎相反(向右移动),除了符号值(即那些可以是负的)用1为负值,其他零它背面填充。



1



移位运算符本质上是MOD的数据的宽度。一个int是32位,因此33(以Int32)已左移是完全一样的1左移你没有得到全部为零。 A 为64位,所以33左移给出了不同的答案(原次2 ^ 33)。



2



每个左移(数据宽度内)是相同的(整数),为×2 - 所以与下; 4;是x2x2x2x2 = x16的。



这是简单的二进制:

  0000000001 = 1 

<<去

  0000000010 = 2 

<<去

  0000000100 = 4 

<<去

  0000001000 = 8 


I can not understand this shift operator (c# reference):

class MainClass1
{
 static void Main()
    {
        int i = 1;
        long lg = 1;
        Console.WriteLine("0x{0:x}", i << 1);
        Console.WriteLine("0x{0:x}", i << 33);
        Console.WriteLine("0x{0:x}", lg << 33);
    }
}

/*
Output:
0x2
0x2
0x200000000
*/

class MainClass2
{
     static void Main()
     {
         int a = 1000;
         a <<= 4;
         Console.WriteLine(a);
     }
}

/*
Output:
16000
*/
解决方案

<< is the left-shift operator; this takes the binary representation of a value, and moves all the bits "n" places to the left (except for "mod", see "1"), back-filling with zeros.

>> is the right-shift operator; this does nearly the opposite (moving to the right), except for signed values (i.e. those that can be negative) it back-fills with 1s for negative values, else zeros.

1:

The shift operator is essentially "mod" the width of the data. An int is 32 bits, so a left shift of 33 (in Int32) is exactly the same as a left shift of 1. You don't get all zeros. A long is 64 bits, so a left-shift of 33 gives a different answer (original times 2^33).

2:

Each left shift (within the data width) is the same (for integers) as x2 - so <<4 is x2x2x2x2 = x16.

This is simple binary:

0000000001 = 1

<< goes to

0000000010 = 2

<< goes to

0000000100 = 4

<< goes to

0000001000 = 8

这篇关于了解移位运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 00:36