4.14 Literal constants

주홍영·2022년 3월 11일
0

Learncpp.com

목록 보기
52/199

Literal constants (usually just called literals) are unnamed values inserted directly into the code. For example:

return 5; // 5 is an integer literal
bool myNameIsAlex { true }; // true is a boolean literal
std::cout << 3.4; // 3.4 is a double literal

Octal and hexadecimal literals

int x{ 012 }; // 0 before the number means this is
따라서 x는 10진수로 10
int x{ 0xF }; // 0x before the number means this
따라서 x는 10진수로 15

C++14 binary literals and digit separators

마찬가지로 prefix로 0b를 붙여서 활용할 수 있다

    int bin{};        // assume 16-bit ints
    bin = 0b1;        // assign binary 0000 0000 0000 0001 to the variable
    bin = 0b11;       // assign binary 0000 0000 0000 0011 to the variable
    bin = 0b1010;     // assign binary 0000 0000 0000 1010 to the variable
    bin = 0b11110000; // assign binary 0000 0000 1111 0000 to the variable

추가로 작은 따옴표로 분리 표시할 수도 있다

    int bin { 0b1011'0010 };  // assign binary 1011 0010 to the variable
    long value { 2'132'673'462 }; // much easier to read than 2132673462

Printing decimal, octal, hexadecimal, and binary numbers

cout은 default로 decimal을 출력한다 이때 std::dec, std::oct, std::hex를 사용해서
진수표현으로 출력할 수도 있다

#include <iostream>

int main()
{
    int x { 12 };
    std::cout << x << '\n'; // decimal (by default)
    std::cout << std::hex << x << '\n'; // hexadecimal
    std::cout << x << '\n'; // now hexadecimal
    std::cout << std::oct << x << '\n'; // octal
    std::cout << std::dec << x << '\n'; // return to decimal
    std::cout << x << '\n'; // decimal

    return 0;
}

binary print

2진수 출력은 조금 어렵다
< bitset > 헤더를 이용해 출력해야 한다

#include <bitset> // for std::bitset
#include <iostream>

int main()
{
	// std::bitset<8> means we want to store 8 bits
	std::bitset<8> bin1{ 0b1100'0101 }; // binary literal for binary 1100 0101
	std::bitset<8> bin2{ 0xC5 }; // hexadecimal literal for binary 1100 0101

	std::cout << bin1 << ' ' << bin2 << '\n';
	std::cout << std::bitset<4>{ 0b1010 } << '\n'; // create a temporary std::bitset and print it

	return 0;
}

이때 출력은 다음과 같다

11000101 11000101
1010

profile
청룡동거주민

0개의 댓글