Reputation: 545
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.
Upvotes: 1
Views: 339
Reputation: 1241
One possible solution is:
unsigned long i = arr.to_ulong();
i = (i & (i >> 4) & (i >> 8) & (i >> 12)) & 0xf;
a = std::bitset<4>(i);
Upvotes: 1
Reputation: 16148
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
);
Upvotes: 2
Reputation: 92211
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!
Upvotes: 2