C# 原码与补码的转换

            /// <summary>
            /// 求一个16位数数的补码
            /// </summary>
            /// <param name="OriginalCode">传入一个Int16整型</param>
            /// <returns></returns>
            public static int ConvertComplementCode(int OriginalCode)
            {
                int a = short.MaxValue;
                int b = short.MinValue;
                int c = a - b;
                int d = 0;
                if (OriginalCode > 0)
                {
                    d = -(c - OriginalCode + 1);
                }
                else
                {
                    d = c + OriginalCode + 1;
                }
                return d;
            }

            /// <summary>
            /// 求一个32位数的补码
            /// </summary>
            /// <param name="OriginalCode">传入一个Int32整型</param>
            /// <returns></returns>
            public static long ConvertComplementCode(long OriginalCode)
            {
                long a = int.MaxValue;
                long b = int.MinValue;
                long c = a - b;
                long d = 0;
                if (OriginalCode > 0)
                {
                    d = -(c - OriginalCode + 1);
                }
                else
                {
                    d = c + OriginalCode + 1;
                }
                return d;
            }
原码与补码互转

 

posted @ 2019-06-20 16:27  鸑鷟虽孤  阅读(4774)  评论(0编辑  收藏  举报