我必须在一个字节中rearagne位.我解决了这个问题:
uint8_t c;
uint8_t string[3];
string1[2] = (((c&(1<<0))!=0)<<6)|
(((c&(1<<1))!=0)<<1)|
(((c&(1<<2))!=0)<<0)|
(((c&(1<<3))!=0)<<2)|
(((c&(1<<4))!=0)<<3)|
(((c&(1<<5))!=0)<<4)|
(((c&(1<<6))!=0)<<5)|
(((c&(1<<7))!=0)<<7);
Run Code Online (Sandbox Code Playgroud)
basicly:
如果bit0为1,则向左移动1 6次.
如果bit1为1,则向左移动1 0次.....
有更好的解决方案吗?
(((c&(1<<x))!=0)<<y)
Run Code Online (Sandbox Code Playgroud)
也可以写成
((c&(1<<x)))<<(y-x))
Run Code Online (Sandbox Code Playgroud)
马上就可以消除每位一次操作.(请记住这y-x是不变的.)
但那不是它.如果您始终应用此转换,您会注意到某些位移动了相同的量.
(( c & 0x01 ) << 6 ) |
(( c & 0x02 ) ) |
(( c & 0x04 ) >> 2 ) |
(( c & 0x08 ) >> 1 ) |
(( c & 0x10 ) >> 1 ) |
(( c & 0x20 ) >> 1 ) |
(( c & 0x40 ) >> 1 ) |
(( c & 0x80 ) )
Run Code Online (Sandbox Code Playgroud)
我们可以分组.
(( c & 0x01 ) << 6 ) |
(( c & 0x82 ) ) |
(( c & 0x78 ) >> 1 ) |
(( c & 0x04 ) >> 2 )
Run Code Online (Sandbox Code Playgroud)
我们将30个操作减少到10个.