鸟语天空
位运算求绝对值
post by:追风剑情 2018-12-8 20:51

示例

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

namespace ConsoleApp5
{
    class Program
    {
        static void Main(string[] args)
        {

            int n = 5;
            Console.WriteLine(Abs(n));

            n = -5;
            Console.WriteLine(Abs(n));

            Console.Read();
        }

        public static int Abs(int x)
        {
            
            int y = x >> 31;

            Console.WriteLine("x: " + IntToBinary(x));
            Console.WriteLine("y: " + IntToBinary(y));
            Console.WriteLine("x^y: " + IntToBinary(x ^ y));
            Console.WriteLine("(x^y)-y: " + IntToBinary((x ^ y)-y));

            return (x ^ y) - y;
        }

        public static string IntToBinary(int val, int bits = 32)
        {
            string final = "";

            for (int i = bits; i > 0;)
            {
                if (i == 8 || i == 16 || i == 24) final += " ";
                final += ((val & (1 << --i)) != 0) ? '1' : '0';
            }
            return final;
        }
    }
}

运行测试

11111.png

评论:
发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容