I have a four byte DWORD that I need to split into four different characters. I thought I knew how to accomplish this but am getting bizarre numbers every time. Here is my code:
// 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);
Ditch the
memcpyand use bit manipulation:ffin the hexadecimal numbers represents a byte of all1bits. This and the&– bitwise AND – will make the bytes that you’re not interested in – at each position –0, and keeping the bits that you are interested in.The
>>shifts in zeros from the left, putting the byte that we want in the most significant position, for the actual assignment. A shift of 8 shifts by a width of one byte, 16 is two bytes, and 24 is three bytes.Visually, looking at
ff, you can imagine that we’re walking the byte indices towards the left.