C#교과서 마스터하기 8. 비트, 시프트 연산자, 조건 연산자

min seung moon·2021년 7월 9일
0

C#

목록 보기
8/54

https://www.youtube.com/watch?v=aUN6p5-Jffs&list=PLO56HZSjrPTB4NxAsEP8HRk6YKBDLbp7m&index=22

1. 비트 연산자

  • &, |, ~, ^
    • &, 둘 다 1일 때 1
    • |, 둘 중 하나라도 1일 때 1
    • ~, 반대
    • ^, 서로 다를 때 1
using System;
using static System.Console;

namespace testProject
{
    class Program
    {
        static void Main(string[] args)
        {
            byte x = 0b1010;
            byte y = 0b1100;

            WriteLine(Convert.ToString(x & y, 2));
            WriteLine(Convert.ToString(x | y, 2));
            WriteLine(Convert.ToString(~x, 2));
            WriteLine(Convert.ToString(x ^ y, 2));
        }
    }
}

2. 시프트 연산자

  • <<, >>
    • <<, 좌측 이동(값 증가)
    • , 우측 이동(값 감소)

using System;
using static System.Console;

namespace testProject
{
    class Program
    {
        static void Main(string[] args)
        {
            byte x = 0b0000_0010;

            WriteLine($"{nameof(x),10} : {Convert.ToString(x, 2).PadLeft(8, '0')} -> {x,3} ");
            WriteLine($"x = x << 1 : {Convert.ToString(x<<1, 2).PadLeft(8, '0')} -> {x<<1, 3}");
        }
    }
}

3. 기타 연산자(삼항(조건)연산자)

  • 조건 연산자(3항연산자)-ConditionalOperator
    • **?:"
    • 조건에 따라 두 값 중에 하나를 연산결과로 전달
    • 뒤에서 배울 if~else문의 단축 표현
  • 형식 : (조건) ? 수식1 : 수식2
    • 조건이 참이면 수식1이 수행, 거짓이면 수식2 수행
      • var result = i > 0 ? 0 : 1;
using System;
using static System.Console;

namespace testProject
{
    class Program
    {
        static void Main(string[] args)
        {
            int number = 10;

            string result = (number % 2 == 0) ? "짝" : "홀";

            WriteLine($"number({number})는 {result} 입니다.");
        }
    }
}

profile
아직까지는 코린이!

0개의 댓글