Get bits from bytes and fragments of 2-bit pairs

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 <string>
//#include <bitset>
#include <iostream>
//using namespace std;
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
+4
source share
2 answers

You can use the same bit manipulation method that you used in Python:

for (std::size_t i = 0; i < s.size(); ++i) {
    for (int j = 0; j < 4; ++j) {
        if (((s[i] >> (2*j)) & 3) == 3) {
            std::cout << i << " " << s[i] << " " << (int)s[i] << " " << j << " " << ((s[i] >> 2*j) & 3) << std::endl;
        }
    }
}

You do not need to use ordit because C ++ character types are integral types and therefore are freely convertible to integers.

.

+6

, n- , -

bit at position x of M = (M & 1<<x) //0 if its zero 1 if its one

+1

Source: https://habr.com/ru/post/1667180/


All Articles