I am new to C ++. In Python 3, I can convert the string “ABC” to selected bits like this and print when the pair of bits is 11:
s = 'ABC'
for i, char in enumerate(s):
for j in range(4):
if ord(char) >> 2*j & 0b11 == 3:
print(i, char, ord(char), j, ord(char) >> 2*j & 0b11)
What returns:
2 C 67 0 3
How to do the same in C ++; that is, how to set bits 1 and 2 of the character "C" to 11? I have this code:
#include <iostream>
int main(){
const int bits_in_byte = 8;
std::string s = "ABC";
for (std::size_t i = 0; i < s.size(); ++i)
{
for (int j = 0; j < 4; ++j) {
std::cout << i << ' ' << s[i] << ' ' << std::bitset<bits_in_byte>(s[i]) << std::endl;
}
}
}
What returns:
0 A 01000001
0 A 01000001
0 A 01000001
0 A 01000001
1 B 01000010
1 B 01000010
1 B 01000010
1 B 01000010
2 C 01000011
2 C 01000011
2 C 01000011
2 C 01000011
source
share