Namespaces
Variants

std::bit_compress

cppreference.net에서
 
 
유틸리티 라이브러리
일반 유틸리티
관계 연산자 (C++20에서 폐지됨)
정수 비교 함수
(C++20)(C++20)(C++20)    
(C++20)
스왑 및 타입 연산
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
공통 어휘 타입
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)



 
비트 조작
(C++20)
(C++23)
2의 정수 거듭제곱2
(C++20)
(C++20)
(C++20)
시프트
(C++29)
(C++29)
회전
(C++20)
(C++20)
카운팅
(C++20)
(C++20)
(C++20)
순열
(C++29)
(C++29)
엔디안
(C++20)
 
헤더 <bit>
template< class T >
constexpr T bit_compress( T x, T m ) noexcept;
에 정의됨 (C++29부터)

x의 비트 중 m에서 1-비트인 위치의 비트를 선택하여 오른쪽으로 연속적으로 채웁니다. 나머지 비트는 0입니다.

이 오버로드는 T이 부호 없는 정수 타입인 경우에만 오버로드 해결에 참여합니다 (즉, unsigned char, unsigned short, unsigned int, unsigned long, unsigned long long 또는 확장 부호 없는 정수 타입).

매개변수

x - 부호 없는 정수 타입의 값
m - 부호 없는 정수 타입의 값

반환값

x에 마스크 m를 통해 비트 패킹을 적용한 결과.

참고 사항

이 함수는 PEXT x86_64 및 BEXT ARM 명령어와 동일한 결과를 갖습니다.

기능 테스트 매크로 값 표준 기능
__cpp_lib_bitops 202606L (C++29) 비트 순열

가능한 구현

template<typename T, typename ... U>
concept neither = (!std::same_as<T, U> && ...);

template<std::unsigned_integral T>
    requires neither<T, bool, char, char8_t, char16_t, char32_t, wchar_t>
constexpr T bit_compress(T x) noexcept
{
    T result = 0;
    for (int i = 0, j = 0; i < std::numeric_limits<T>::digits; ++i)
    {
        bool mask_bit = (m >> i) & 1;
        result |= (mask_bit & (x >> i)) << j;
        j += mask_bit;
    }
    return result;
}

예제

#include <bit>
#include <cstdint>

static_assert(
    std::bit_compress(
        std::uint16_t{0xABCD}, // source
        std::uint16_t{0x0F0F}) // mask
    ==  std::uint16_t{0x00BD}  // result
);
static_assert(
    std::bit_compress(
        std::uint8_t{0b0100'1001}, // source
        std::uint8_t{0b1100'1100}) // mask
    ==  std::uint8_t{0b0000'0110}  // result
);

int main() {}

같이 보기

마스크를 사용하여 피연산자에서 비트를 확장합니다 (PDEP)
(함수 템플릿)