How to get the 4 least significant bits in a byte with C++

1 Answer

0 votes
#include <iostream>
#include <cstdint>
#include <bitset>

int main() {
    uint8_t byteValue = 0b11010110;   
    uint8_t lower4 = byteValue & 0x0F; // mask with 00001111 to  keep only the 4 LSBs

    // Print numeric values
    std::cout << "Original byte (decimal): " << +byteValue << "\n";
    std::cout << "Lower 4 bits (decimal): " << +lower4 << "\n\n";

    // Print as bits
    std::cout << "Original byte (bits): " << std::bitset<8>(byteValue) << "\n";
    std::cout << "Lower 4 bits (bits):   " << std::bitset<4>(lower4) << "\n";
}

 
 
/*
run:
 
Original byte (decimal): 214
Lower 4 bits (decimal): 6

Original byte (bits): 11010110
Lower 4 bits (bits):   0110
 
*/

 



answered Dec 27, 2025 by avibootz
edited Dec 27, 2025 by avibootz
...