Reputation: 1727
I am implementing DES algorithm and I need to split std::bitset<56> permutationKey
in two halves.
std::bitset<56> permutationKey(0x133457799BBCDF);
std::bitset<28> leftKey;
std::bitset<28> rightKey;
std::bitset<56> divider(0b00000000000000000000000000001111111111111111111111111111);
rightKey = permutationKey & divider;
leftKey = (permutationKey >> 28) & divider;
I tried to typecast bitset<56>
to bitset<28>
but it didn't work.
Other way to achieve the same thing is to iterate and assign each bit individually. I want to achieve it without using loops there must be another way.
I was able to do it with primitive types
uint64_t key = 0b0001010101010101110110001100001110000011111100000000011111000000;
//00010101.01010101.11011000.11000011---|---10000011.11110000.00000111.11000000
uint32_t right = (uint32_t)key;
uint32_t left = key >> 32;
How can I split bitset
like this?
Upvotes: 5
Views: 3327
Reputation: 1973
The proposed solution in previous answer is nice but not general: how do we split a bitset that is to big to be converted to u_long
without loss of bits?
Intuitively we look here for something like iterators and ranges:
vector<int> vec({1,2,3,4});
vector<int> vec1(vec.begin(), vec.begin() + vec.size() / 2); // {1,2}
vector<int> vec2(vec.begin() + vec.size() / 2, vec.end()); // // {3,4}
Unfortunately bitsets do not have iterators and ranges. If you do not care much about speed of conversion I would propose following simple and general solution:
const size_t size = ... // we assume size is even
bitset<size> bss;
.......
const string str = bss.to_string();
bitset<size/2>bss1(str.substr(0, str.size() / 2)); // first half
bitset<size/2>bss2(str.substr(str.size() / 2, str.size())); // second half
Upvotes: 2
Reputation: 69882
std::bitset<56> permutationKey(0x133457799BBCDF);
std::bitset<56> divider(0b00000000000000000000000000001111111111111111111111111111);
auto rightKey = std::bitset<28> ( (permutationKey & divider).to_ulong() );
auto leftKey = std::bitset<28> ( ((permutationKey >> 28) & divider).to_ulong() );
Upvotes: 6