更新时间:2023-11-09 22:51:28
某些按位操作可以解决问题.
Some bitwise operations can do the trick.
#include <inttypes.h>
int main(){
uint8_t rows[8] = {
0b11111111,
0b00000001,
0b00000001,
0b00111111,
0b00000001,
0b00000001,
0b00000001,
0b11111111
};
uint8_t rows2[8] = {0, 0, 0, 0, 0, 0, 0, 0};
uint8_t rows3[8] = {0, 0, 0, 0, 0, 0, 0, 0};
int i, j;
// rotate clockwise
for(i=0; i<8; ++i){
for(j=0; j<8; ++j){
rows3[i] = ( ( (rows[j] & (1 << (7-i) ) ) >> (7-i) ) << j ) | rows3[i];
}
}
// rotate anti-clockwise
for(i=0; i<8; ++i){
for(j=0; j<8; ++j){
rows2[i] = ( ( (rows[j] & (1 << i ) ) >> i ) << (7-j) ) | rows2[i];
}
}
}
在顺时针方向上,使用(rows[j] & (1 << (7-i) ) ) >> (7-i)
获取第j个原始字节的第(7-i)个位,然后将其移至第j个位置.通过对字节本身执行或"(|
)来收集所有位,因此将数组初始化为0非常重要.
逆时针情况类似,更改了索引.
我用另一封信对其进行了测试,可以让您确定旋转是否正常工作.如果您需要进一步的解释,请问.
In the clockwise case, you get each (7-i)-th bit of the j-th original byte with (rows[j] & (1 << (7-i) ) ) >> (7-i)
and then shift it to the j-th position. You collect all the bits by doing an "or" (|
) with the byte itself, so it is very important to initialize the array with 0s.
The anti-clockwise case is analogous, changing the indexing.
I used another letter to test it, that let you know for sure if the rotation is working properly. If you need further explanation, please just ask.
If you want to look the result, I'm using the function in this SO question: Is there a printf converter to print in binary format?