Reputation: 1022
I have a variable and it's type is bitset<16>. I want to get first 8 bit of my variable and put it into char variable. I know how to convert bitset to char, but I don't know how to select first 8 bit and convert it to char.
Upvotes: 5
Views: 2559
Reputation: 1641
From the doc of the std::bitset constructor:
If the value representation of val is greater than the bitset size, only the least significant bits of val are taken into consideration.
So another solution could be:
#include <iostream>
int main() {
std::bitset<16> myBits16(0b0110110001111101);
std::bitset<8> myBits8(myBits16.to_ulong());
char reg = static_cast<char>(myBits8.to_ulong());
}
Upvotes: 2
Reputation: 348
If by "first 8 bits" you're talking about 8-MSB, consider using the >> operator :
#include <iostream>
int main() {
std::bitset<16> myBits(0b0110110001111101);
char reg = 0;
reg = static_cast<char>(myBits.to_ulong() >> 8);
}
Upvotes: 4