C++, 3.연산자들

이도현·2023년 8월 9일
0

1. 연산자 우선순위와 결합법칙

위키피디아 연산자 우선수위
https://ko.wikipedia.org/wiki/C%EC%99%80_C%2B%2B%EC%9D%98_%EC%97%B0%EC%82%B0%EC%9E%90

수식을 작성할 때 가독성을 위해 우선순위로 하고자하는 식에 ()붙이는 것을 권장한다.

#include <iostream>
#include <cmath> //pow를 쓰게 해줌

using namespace std;

int main()
{
    int x = std:: pow(2,3) // 2의 3제곱

    cout << x << endl;

    return 0;
}

예제
r = 1 + 2 + 3 * 4
a = b = b
t /= --w + 5
a || b && c || d
위의 식들을 위키피디아 링크를 참조하여 우선순위 파악해보기 정답은 따로 기재하지 않겠음.

2. 산술연산자

( +, - ,* , / , %)

int x = 7;
int y = 4;

cout << x / y << endl; //둘 다 정수형임으로 소수는 버리고 정수만 표현됨.
cout << flaot(x) / y << endl; // 정답에 소수가 포함됨. 하나라도 소수형으로 표현하도록 허용했기 때문

3. 증감연산자

#include <iostream>

using namespace std;

int main()
{
	int x = 6, y = 6;
	cout << x << " " << y << endl;
	cout << ++x << " " << --y << endl;
	cout << x << " " << y << endl;
	cout << x++ << " " << y-- << endl;
	cout << x << " " << y << endl;

	return 0;
}

찍어보고 이해하기(증감 연산자 ++, --위치에 따른 순서에 대해 깊이있게 이해해보기)

4. sizeof, 쉼표 연산자, 조건부 연산자

#include <iostream>

using namespace std;

int main()
{
	//sizeof
	float a;

	sizeof(float); //타입을 넣어도 되고
	sizeof(a);     //변수를 넣어도 됨

	//comma operator,(그냥 구분하는 , 와 구분할 수 있으면 좋음)
	int x = 3;
	int y = 14;
	//int z = (++x, ++y); 아래의 과정을 간단하게 사용 가능
	++x;
	++y;
	int z = y;

	int a = 1. b = 14;
	int z;

	z = (a--, a * b); // ()로 감싸주지 않으면 a--가 우선적으로 대입되어 
	                  // cout 사용 시 a--값만 나온다.

	// conditional operator(3항 연산자로 쓰이지만 나중에 조건부 연산자에
	//                      3항 연산자가 아닌 것이 추가 될 수 있으므로 같다고 
	//					    생각하면 안된다.)
	
	return 0;
}

5. 관계연산자

(< , > , ==, !==)

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
	double d1(100 - 99.99); //0.001
	double d2(10 - 9.99);   //0.001

	cout << std::abs(d1 - d2) << endl; // 5.32907e-15

	return 0;
}

왜 d1 - d2가 다른지는 수치해석학에서 배울 수 있다. 필요한 경우 추가적으로 공부하고 일단은 둘이 같지 않는다는 것은 당연한 것이니 외우자.

6. 논리연산자

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
	bool x = true;
	bool y = false;
	// logical NOT
	cout << !x << endl;

	// logical AND
	cout << (x && y) << endl;
	
	// logical OR
	cout << (x || y) << endl;

	int a = 5;
	int b = 7;

	if (!(x == y))//!를 붙이지 않으면 (!x) == y로 인식된다.
	{
		cout << "a does not equal y" << endl;
	}

	// De Morgan's Law
	!(x && y); // !x || !y;로 바뀐다.
	!x && !y; // 이렇게 바뀐다고 착각하지말자.

	// XOR
	// false fasle false
	// false true true
	// true flase true
	// true true false

	return 0;
}
  • 생각해보기(무엇을 뜻 하는지 말로 해보고 넘어가자)

(true && true) || false
(false && true) || true
(false && true) || false || true
(14 > 13 || 2 > 1) && (9 > 1)
!(2314123 > 2 || 123123 > 2387

7. 이진수 Binary Number

0101 1110

2^70 + 2^61 + 2^50 + 2^41 + 2^31 + 2^21 + 2^11 + 2^10
= 1280 + 641 + 320 + 161 + 81 + 41 + 21 + 10
= 64 + 2+ 8 + 4 + 2
= 94

이 귀찮은 과정을 컴퓨터가 알아서 해준다. 진짜 다행이다.


148(deciaml to binary) - 10진수를 2진수로 바꿔준다.

148 / 2 =74 r0 (r = reminder)
74 / 2 = 37 r0
37 / 2 = 18 r1
18 / 2 = 9 r0
9 / 2 = 4 r1
4 / 2 = 2 r0
2 / 2 = 1 r0
1 / 2 = 0 r1

1001 0100


-5

0000 0101

  • 보수 complement

1111 1010
1111 1011 <- -5

(보수의 대한 개념은 좀 더 공부가 필요할 수 있다.)

생각해보기

이진수 0100 1101을 10진수로
10진수 93을 8비트 무부호 정수로
10진수 -93을 8비트 부호 정수로
2진수 1010 0010을 무부호 10진수로
같은 2진수를 부호가 있는 10진수로

8. 비트단위 연산자

#include <iostream>
#include <bitset>//bitset사용하게 하여 편의성 기능함.

using namespace std;

int main()
{
	// << left shift
	// >> right shift
	/*
	~(bitwise NOT), 
	&(bitwise AND),
	|(bitwise OR)
	^(bitwise XOR)
	bitwiseoperators 사용시 언사인드 사용이 통상적
	*/
	unsigned int a = 0b1100; // 이진수 표현 앞에는 0b를 붙인다.
	unsigned int b = 0b0110;

	cout << std::bitset<16>(a) << endl;

	cout << std::bitset<16>(~b) << endl;
	
	return 0;

}

찍어보고 cout << std::bitset<16>(~b) << endl; 이줄에서 ~대신 다른연산자 삽입해서 기능 확인해보기.

9. 비트 플래그, 비트 마스크 사용법

  • 비트플래그 사용법
#include <iostream>
#include <bitset>

using namespace std;

int main()
{
	

	/* bool type으로 아이템 하나하나 상태를 확인하는 것은 비효율적
	bool item1_flag = false;
	bool item2_flag = false;
	bool item2_flag = false;
	bool item4_flag = false;
	.....
	*/
	
	//bit flag를 활용
	const unsigned char opt0 = 1 << 0;
	const unsigned char opt1 = 1 << 1;
	const unsigned char opt2 = 1 << 2;
	const unsigned char opt3 = 1 << 3;
	
	cout << bitset<8>(opt0) << endl;
	cout << bitset<8>(opt1) << endl;
	cout << bitset<8>(opt2) << endl;
	cout << bitset<8>(opt3) << endl;

	unsigned char items_flag = 0;
	cout << "No item" << bitset<8>(items_flag) << endl;

	// item0 on
	items_flag |= opt0;
	cout << "Item0 obtained" << bitset<8>(items_flag) << endl;

	// item3 on
	items_flag |= opt3;
	cout << "Item3 obtained" << bitset<8>(items_flag) << endl;
	
	// item3 lost
	items_flag &= opt3;
	cout << "Item3 lost" << bitset<8>(items_flag) << endl;
	
	// has item ?
	if (items_flag & opt1)
	{
		cout << "Has item1" << endl;
	}
	
	// obtain item 2, 3
	items_flag |= (opt2 | opt3);
	cout << "Item2, 3 obtained" << bitset<8>(items_flag) << endl;

	return 0;
}

비트마스크 활용법(비트마스크예제로는 color table이 애용된다.)
https://www.rapidtables.com/web/color/RGB_Color.html

RGB Color Codes Chart 
RGB Color Codes Chart RGB color picker | RGB color codes chart | RGB color space | RGB color format and calculation | RGB color table RGB color picker R G B H ° S % V % # RGB color codes chart Hover with cursor on color to get the hex and decimal color codes below: RGB color space RGB color space or...
www.rapidtables.com
컬러테이블은 16진수로 나열되는게 통상적이다.

#include <iostream>
#include <bitset>

using namespace std;

int main()
{
	const unsigned int red_mask = 0xFF0000;
	const unsigned int green_mask = 0x00FF00;
	const unsigned int blue_mask = 0x0000FF;

	cout << std::bitset<32>(red_mask) << endl;
	cout << std::bitset<32>(green_mask) << endl;
	cout << std::bitset<32>(blue_mask) << endl;
	//출력되어 1이 차있는 곳이 색깔 값이다.'

	unsigned int pixel_color = 0xDAA520;

	cout << std::bitset<32>(pixel_color) << endl;
	
	//pixel color에서 blue color 값반 추출
	unsigned char blue = pixel_color & blue_mask;

	cout << "blue: " << bitset<8>(blue) << " " << int(blue) << endl;

	return 0;
}

예제
위의 내용에서 green 값이 이진수 8자리수와 10진수 2자리수로 나오게 작성해보라

정답:
https://blog.naver.com/ehgus8621/222921333376

#include <iostream>
#include <bitset>

using namespace std;

int main()

{

const unsigned int red_mask = 0xFF0000;

const unsigned int green_mask = 0x00FF00;

const unsigned int blue_mask = 0x0000FF;

​

cout << std::bitset<32>(red_mask) << endl;

cout << std::bitset<32>(green_mask) << endl;

cout << std::bitset<32>(blue_mask) << endl;

//출력되어 1이 차있는 곳이 색깔 값이다.'unsigned int pixel_color = 0xDAA520;

​

cout << std::bitset<32>(pixel_color) << endl;//pixel color에서 blue color 값반 추출

unsigned char blue = pixel_color & blue_mask;

unsigned char green = (pixel_color & green_mask) >> 8;

​

cout << "blue: " << bitset<8>(blue) << " " << int(blue) << endl;

cout << "green: " << bitset<8>(green) << " " << int(green) << endl;

return 0;

}

빨간색 부분이 추가되어야 정답.

profile
좋은 지식 나누어요

0개의 댓글