Pla*_*oks 2 c c++ memory algorithm
我有一个四字节的DWORD,我需要分成四个不同的字符.我以为我知道怎么做到这一点但每次都得到奇怪的数字.这是我的代码:
// The color memory
int32 col = color_mem[i];
// The four destination characters
char r, g, b, a;
// Copy them in advancing by one byte every time
memcpy(&r, &col, 1);
memcpy(&g, &col + 1, 1);
memcpy(&b, &col + 2, 1);
memcpy(&a, &col + 3, 1);
Run Code Online (Sandbox Code Playgroud)
pb2*_*b2q 10
抛弃memcpy
并使用位操作:
r = (col & 0x000000ff);
g = (col & 0x0000ff00) >> 8;
b = (col & 0x00ff0000) >> 16;
a = (col & 0xff000000) >> 24;
Run Code Online (Sandbox Code Playgroud)
ff
十六进制数字表示所有1
位的字节.这个和&
- 按位AND - 将使你不感兴趣的字节 - 在每个位置 - 0
,并保留你感兴趣的位.
在>>
从左侧零转移,把我们要在最显著位置的字节,对于实际分配.8个移位宽度为1个字节,16个为2个字节,24个为3个字节.
从视觉上看ff
,你可以想象我们正在将字节索引向左移动.