简体   繁体   中英

C++ Do operation on bits of a std::bitset

I want to AND 4 4-bits of a std::bitset<16> with each other. I mean:

std::bitset<16> arr("1100 1100 1100 1100");

I want to AND these 4-bits array.

std::bitset<4> a;

a= 1100 & 1100 & 1100 & 1100

I want to do this in the most efficient way. Not using for loops.

Thanks in Advance.

There is no shortcut with slicing bitsets. Just work your way through the bits

a[0] = arr[0] & arr[4] & arr[8] & arr[12];

etc.

It can't take the computer long to check 16 bits, however you do it!

so long as you know how many bits the target and source are you can do this.

std::bitset<16> arr("1100110011001100");
std::bitset<4> v (
    ((arr    ) & 
     (arr>>4 ) & 
     (arr>>8 ) & 
     (arr>>12)).to_ulong() 
     &   0x0f
);

One possible solution is:

unsigned long i = arr.to_ulong();
i = (i & (i >> 4) & (i >> 8) & (i >> 12)) & 0xf;
a = std::bitset<4>(i);

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