bit — 비트 조작
bit — 비트 조작 (Bit manipulation)
비트 조작(bit manipulation) 라이브러리는 개별 비트와 비트 시퀀스를 접근·조작·처리하는 여러 함수 템플릿을 제공해요. C++20에서 도입됐어요. <bit> 헤더에 있어요.
출처: cppreference
본문
주요 함수
<bit> 헤더, std 네임스페이스
비트 캐스팅·변환
std::bit_cast— 비트 패턴을 그대로 유지해 타입 재해석 (C++20)std::byteswap— 바이트 순서 뒤집기 (C++23)
비트 회전·이동
std::rotl,std::rotr— 비트 회전 (C++20)std::countl_zero,std::countr_zero— 앞/뒤 0 개수std::countl_one,std::countr_one— 앞/뒤 1 개수
비트 개수·검출
std::popcount— 1인 비트 수std::has_single_bit— 2의 거듭제곱인지
비트 폭·지수
std::bit_width— 값을 나타내는 비트 폭std::bit_ceil,std::bit_floor— 2의 거듭제곱 반올림
#include <bit>
#include <cstdint>
#include <iostream>
std::popcount(0b1011u); // 3
std::has_single_bit(8u); // true (8 = 2^3)
std::bit_width(10u); // 4 (10 = 0b1010)
std::bit_ceil(6u); // 8
std::bit_floor(6u); // 4
std::countl_zero(0x0Fu); // 28 (32비트 기준)
bit_cast 예
#include <bit>
#include <cstring>
// float를 그 비트가 해석하는 int로 (reinterpret_cast의 안전한 대안)
float f = 1.0f;
std::uint32_t bits = std::bit_cast<std::uint32_t>(f);
특징
- 대부분
constexpr— 컴파일 타임에도 비트 연산 가능. - 난해한 비트 논리를 표준·이식성 있게 제공해요.
bit_cast는 UB 없이 비트 재해석을 안전하게 수행해요.
constexpr auto bits = std::popcount(0xFFu); // 8 (컴파일 타임)
<bit> 라이브러리는 비트 단위 알고리즘을 이식성 있고 constexpr로 다루는 현대 C++의 표준 도구예요.