프로그래밍/C++
C++ ] uint8_t, int_8t를 스트림 연산자(<<)로 출력할 때의 문제점
eteo
2025. 4. 18. 22:20
C++에서 char, singed char, unsigned char 타입은 스트림 연산자(<<)를 사용해서 stdout, file, stringstream 등에 출력시 모두 문자형 데이터로 처리된다.
uint8_t와 int8_t도 내부적으로 각각 unsigned char, singed char로 정의되어 있기 때문에 마찬가지이다.
즉, C++에서 8비트 데이터 타입 중 std::ostream << 연산자를 사용할 때 기본적으로 정수로 출력되는 데이터 타입은 존재하지 않는다.
#include <iostream>
#include <cstdint>
int main() {
char c = 65;
signed char sc = 66;
unsigned char uc = 67;
uint8_t u8 = 68;
int8_t i8 = 69;
std::cout << "char: " << c << std::endl; // ASCII 'A'
std::cout << "signed char: " << sc << std::endl; // ASCII 'B'
std::cout << "unsigned char: " << uc << std::endl; // ASCII 'C'
std::cout << "uint8_t: " << u8 << std::endl; // ASCII 'D'
std::cout << "int8_t: " << i8 << std::endl; // ASCII 'E'
return 0;
}
때문에 해당 타입을 정수로 출력하기 위해서는 명시적으로 다른 정수 데이터 타입으로 캐스팅을 하거나,
std::cout << "정수로 출력: " << static_cast<int>(u8) << std::endl;
출력 연산자를 오버로드 처리하는게 필요하다. 다만 아래와 같이 했을 때 unsigned char, singed char 타입을 문자로 출력하려면 또 다시 캐스팅이 필요하다.
std::ostream& operator<<(std::ostream& os, const uint8_t& value) {
return os << static_cast<int>(value);
}
std::ostream& operator<<(std::ostream& os, const int8_t& value) {
return os << static_cast<int>(value);
}