problem about cute patterns

when solving, bit operations are used, in which I know nothing. Is there a way to replace this code, which takes a long time through some kind of programmer (bit operations like &, <<, >>) method?

for(i=0;i<=m-2;i++){ string k1 = bitset<30>(p1).to_string(); reverse(k1.begin(), k1.end()); string k3 = bitset<30>(p2).to_string(); reverse(k3.begin(), k3.end()); b[1] = k1.at(i); b[2] = k1.at(i+1); b[3] = k3.at(i); b[4] = k3.at(i+1); if (b[1] == '1' && b[2] == '1' && b[3] =='1' && b[4] == '1'){ // квадрат в строках i и i + 1 чрный xx = false; } if ((b[1] == '0') &&(b[2] == '0') && (b[3] == '0') && (b[4] == '0')) { // квадрат в строках i и i + 1 белый xx = false; } } return xx; } 

  • Hmm, tin. who is interesting invented so work with bats. it cannot even be called bit operations. here they are processed as strings ... And yes, you are right, if you process it as double-digit numbers, the speed will be several orders higher. Actually, what do you not understand in this code? The main thing is to learn to do reverse. and the rest is nonsense, they took a couple of bits from one number, a couple from another, they were convinced that the result was 0b1111 or 0 - Mike

1 answer 1

Since there is a size limit of 30, you can store the slice in a 32-bit integer. Allocation of the i-th bit:

 bit(v, i) = (v >> i) & 1; 

A check for all black or white:

 if ((bit1 || bit2 || bit3 || bit4) == 0) if ((bit1 && bit2 && bit3 && bit4) == 1) 

Another variant of simultaneous testing on both black and white squares:

 if (((bit1 + bit2 + bit3 + bit4) & 3) == 0)