有符号类型无符号类型转换

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace testBinary
{
    class Program
    {
        static void Main(string[] args)
        {
            //Convert.ToByte 默认字节表示范围为  0 ~ 255 , 负数,正数,实质表示范围不同。 最高位是符号位,还是无符号位。

            Console.WriteLine("0xff 二进制(0 ~ 255):{0}", Convert.ToString(0xff, 2));


            //-128 ~ 128 转 0 ~ 255 , 将符号位当作数值
            int udata = -42 , data = 214;
            Console.WriteLine("-42转无符号:{0}", -42 & 0xff);

            //以上等效 如下:取末七位 ,然后加上第8位数值
            Console.WriteLine((udata & ((1 << 7) - 1))  + Math.Pow(2 , 7));

            //以上等效 如下: 取末七位 ,  将第 8 位 置为 1
            Console.WriteLine( (udata & ((1 << 7) - 1)) | (1 << 7));

            //以上等效
            Console.WriteLine((udata & ((1 << 8) - 1)));

            //以上等效
            Console.WriteLine((udata & 0xff));

            //无符号转有符号 , 只针对负数 如 -42
            sbyte ss = (sbyte)1;
            ss = (sbyte)((ss << 7) | (data & ((1 << 7) - 1)));
       // ss = (sbyte)data ; //c# 内部转换 Console.WriteLine("无符号转有符号:{0} {1} (8位表示:{2})", ss, Convert.ToString(ss , 2) , Format(ss)); //加减法运算 //有符号转无符号 Console.WriteLine("加减法运算转无符号:{0}", udata < 0 ? udata + 0xff : udata); //无符号转有符号 Console.WriteLine("加减法运算转无符号:{0}", udata > 127/* 1 << 7 */ ? udata - 0xff : udata); Console.ReadKey(); } /// <summary> /// sbyte 类型转为二进制字符串形式 /// </summary> /// <param name="ss"></param> /// <returns></returns> static string Format(sbyte ss) { char[] str = new char[8]; for (int i = 7; i >= 0; i--) { str[i] = (char)(48 + (ss & 1)) ; ss >>= 1; } return new string(str); } } }
原文地址:https://www.cnblogs.com/a_bu/p/5534092.html