简体   繁体   中英

Bit masking with hexadecimal in c++

I need to mask my output in binary with hexadecimals variables. Do I need to convert the binary output to hexadecimal (or hexadecimals variables to binary)? Or is there any way in C++ to directly mask them and store it to a new variable?

#Edit : The binary output is stored to a std::bitset variable.

The use of bitset wasn't mentioned in your question, improve on that next time. You need to create a bitmask for the hex value as well. Then you can just & the bitmasks

#include <bitset>
#include <iostream>

int main()
{
    std::bitset<8> value{ 0x03 };
    std::bitset<8> mask{ 0x01 };
    std::bitset<8> masked_value = value & mask;

    std::cout << value.to_string() << " & " << mask.to_string() << " = " << masked_value.to_string() << "\n";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM