using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; namespace ConsoleApplication1 { public class 位运算 { static void Main(string[] args) { //new demo(FontStyle.Bold | FontStyle.Italic); // Console.WriteLine(new demo(12 | 7).GetBit(7)); //8位,一个字节 //0 0 0 0 0 1 1 1 //0 0 0 0 0 1(2的2次幂) 1(2的1次幂) 1(2的0次幂) //0+0+0+0+0+4+2+1=7 //1 1 1 1 1 0 0 1 //1(==1,负数) 1 1 1 1 0 0 1 //0 0 0 0 0 1(2的-2次幂) 1(2的-1次幂) 0 -1(负数都-1) //0+0+0+0+0+-4+-2-1=-7 //0000 0000 0000 0000 0000 0000 0000 0111 32位的7 //1111 1111 1111 1111 1111 1111 1111 1001 32位的-7 //右移 正数补0,负数补1, 左移 都补0 //-7 >> 2 -7右移2位 //1111 1111 1111 1111 1111 1111 1111 1001 -1-1=-2 补位1 //111111 1111 1111 1111 1111 1111 1111 10 //01 //7 >> 2 //000000 0000 0000 0000 0000 0000 0000 01 //10 1 补位0 //7 << 2 //0000 0000 0000 0000 0000 0000 0000 0111 32位的7 //0000 0000 0000 0000 0000 0000 0001 1100 16+8+4=28 //-7 <<2 //1111 1111 1111 1111 1111 1111 1111 1001 //1111 1111 1111 1111 1111 1111 1110 0100 -16-8-2-1-1=-28 //-(2n-1-1)~+(2n-1-1),其中n为机器字长。原码表示的整数范围是 Console.WriteLine(~(S的M次方(2, 64 - 1) - 1)); //Console.WriteLine("long最大值" + long.MinValue); //~ 运算符对操作数执行按位求补运算,其效果相当于反转每一位。按位求补运算符是为 int、uint、long 和 ulong 类型预定义的 int[] values = { 0, 0x111, 0xfffff, 0x8888, 0x22000022, 7, -7 }; foreach (int v in values) { Console.WriteLine("0x{0:x8} = ~0x{1:x8} = {2}", v, ~v, v); } Console.Read(); } static long S的M次方(int s, int m) { int jdz = Math.Abs(m); long n = s; for (int i = 1; i < jdz; i++) { n *= s; // Console.WriteLine(n); } if (m < 0) n *= -1; else if (n == 0 && m == 0) n = 0; else if (m == 0) n = 1; return n; } } public class demo { public demo(FontStyle style) { long i = 0; // Label_0253: goto 标记标签 Console.WriteLine(style + " " + (++i)); // goto Label_0253; } public demo(int b) { Console.WriteLine(b); } public string GetBit(int value) { int size = 32; int mask = 1 << size - 1;//掩码 //0000 0000 0000 0000 0000 0000 0000 0001 =1 //1 << 31 //1000 0000 0000 0000 0000 0000 0000 0000 =-2147483648,int.minValue Console.WriteLine("mask:" + mask); string s = ""; char bit; for (int i = 0; i < size; i++) { bit = (mask & value) > 0 ? '1' : '0'; Console.WriteLine(mask + "&" + value); s += bit; mask >>= 1; } //第一次循环 i=0 //1000 0000 0000 0000 0000 0000 0000 0000 //0000 0000 0000 0000 0000 0000 0000 0111 //0000 0000 0000 0000 0000 0000 0000 0000 =0 bit=0 //第二次循环 i=1 mask>>1 //1100 0000 0000 0000 0000 0000 0000 0000 //0000 0000 0000 0000 0000 0000 0000 0111 //0000 0000 0000 0000 0000 0000 0000 0000 =0 bit=0 //第32次循环 i=31 mask>>31 //1111 1111 1111 1111 1111 1111 1111 1111 //0000 0000 0000 0000 0000 0000 0000 0111 //0000 0000 0000 0000 0000 0000 0000 0111 =7 bit=1 return s; } } }