一些常用位运算示例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace testBinary
{class Program{static int absolute(Int32 a) {//return ((a >> 31) & 1) == 1 ? ~a + 1 : a;//a >> 31 , 結果 0xFFFFFFFF , 十進制值: -1;// a ^ 0xFFFFFFFF (取反,補碼)// a ^ 0xFFFFFFFF - (-1) , 值為取反加 1 ;return (a ^ (a >> 31)) - (a >> 31); }static void Main(string[] args){//Console.WriteLine(5 >> 31);//負數二進制表示為, 原碼的補碼 + 1//正數二進制正是原碼.//Console.WriteLine(Convert.ToString( -28 >> 2 , 2));//Console.WriteLine(Convert.ToString( -28 >> 4 , 2));//Console.WriteLine(Convert.ToString(-28 >> 6, 2));//按位或Console.WriteLine((Convert.ToInt16("100100", 2) | Convert.ToInt16("111", 2)) == Convert.ToInt16("100111", 2));uint i = 0, l = 1;//判斷奇偶性 n = 11Console.WriteLine((11 & 1) == 1);//取反求模Console.WriteLine((~i + i) == uint.MaxValue);// i 為無符號 0Console.WriteLine(~i);//求 -1 的表示形式Console.WriteLine( Convert.ToString( ~1 + 1 , 2));//負數位運算,右移,高位默認補1//求模Console.WriteLine( Convert.ToString( ~i , 2));//求絕對值Console.WriteLine("絕對值:{0}", absolute(-5));//Console.ReadKey();
Console.WriteLine(Convert.ToInt16("10010101", 2) & (~0));Console.WriteLine(((l << 3) - 1) & Convert.ToInt16("10010101", 2));//第k 位取反 , k = 5Console.WriteLine(Convert.ToInt16("10010101", 2) ^ (1 << 4));Console.WriteLine(Convert.ToInt16("10000101", 2));//取末4位Console.WriteLine(Convert.ToInt16("10010101", 2) & ((1 << 5) - 1));Console.WriteLine(Convert.ToInt16("10101", 2));//取右邊第k位 k=3Console.WriteLine(Convert.ToInt32("10010101", 2) >> 2 & 1);//第k 位改成 1 k = 4Console.WriteLine(Convert.ToInt32("10010101", 2) | (1 << 5));Console.WriteLine(Convert.ToInt32("10110101", 2));//把第k 位改成 0 , k = 3Console.WriteLine(Convert.ToInt32("10010101", 2) & ~(1 << 2));Console.WriteLine(Convert.ToInt32("10010001", 2));//末K位取反Console.WriteLine(Convert.ToInt32("10010101", 2) ^ ((1 << 3) - 1));Console.WriteLine(Convert.ToInt32("10010010", 2));//初使化k 位初使位為1 的數Console.WriteLine(((UInt32)1 << 16) - 1);Console.WriteLine(Convert.ToUInt16("1111111111111111", 2));//獲取 16位最大值Console.WriteLine(0xFFFF);Console.WriteLine(Convert.ToString((uint)(~(uint)0), 2));//Console.WriteLine( Convert.ToString( ~(uint)5 + (uint)5 , 2));//負數以補碼表示 , 如 -5 表示為: 11111011Console.WriteLine( ((1 << 24) - 1) << 8 | Convert.ToByte("11111011", 2));//已知一個補碼為11111001,則原碼是10000111(-7), 通過位運算證明。Console.WriteLine(Convert.ToByte("11111001", 2) | (((1 << 24) - 1) << 8));////求補碼 , -7 原碼是 00000111 , 取反 ~(00000111) + 1 //Console.WriteLine(Convert.ToString(-7, 2));//加法運算,包含進位Console.WriteLine( Convert.ToString( ~8 + 1 , 2));//位運算不包含進位Console.WriteLine(Convert.ToString(~8, 2));//將末位取反Console.WriteLine(Convert.ToString(~8 ^ 1, 2));//取第k位值 , k = 3 , 10011110Console.WriteLine("第k 位值:{0}" , (158 >> 7 ) & 1);Console.WriteLine("第k 位值:{0}", (158 >> 6) & 1);Console.WriteLine("第k 位值:{0}", (158 >> 5) & 1);Console.ReadKey();}}
}
?
轉載于:https://www.cnblogs.com/a_bu/p/5509317.html
總結
- 上一篇: 原创:安徽“最委屈”的城市,经常被人读错
- 下一篇: FastJSON 简介及其Map/JSO