본문 바로가기

C계열/C#

[c#] Two's compliment(2의 보수)

코드

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

namespace test
{   
    class Program
    {
        static string bindgits(int n, int bits)
        {
            string s;
            s = Convert.ToString(n, 2);
            s = s.PadLeft(bits, '0');
            
            if (n<0)
            {
                s=s.Substring(bits);
            }
  
            return s;

        }

        static void Main(string[] args)
        {
            Console.WriteLine(bindgits(, 16));    #1111111011000011
        }
    }
}

 

내용

이 블로그 직전 게시물인 Python3로 구현한 2의 보수 프로그램을 c#으로 옮긴 것 약간 억지 느낌이다 

 

출처 

직전 게시물

https://parading.tistory.com/61

 

[python3] Two's compliment(2의 보수)

코드 def bindigits(n, bits): s = bin(n & int("1"*bits, 2))[2:] # int("1111111111111111", 2)""안의 숫자를 int단위로 2진수 표시, [2:]는 앞의 0b제거 # int("111",2) 결과 값은 7, bin(int"111",2) 결과 값..

parading.tistory.com

 

간단하게 2의 보수를 확인하고 싶다면

https://www.rapidtables.com/convert/number/decimal-to-binary.html?x=-7

 

Decimal to Binary Converter

Divide by the base 2 to get the digits from the remainders: Divisionby 2 Quotient Remainder(Digit) Bit #

www.rapidtables.com