Set Pixel

Setting an arbitrary pixel in a buffer requires calculating the memory offset, packing the colour into a variable and copying the colour into the buffer.

Calculating Memory Offset

The buffer holding the screen data is comprised of bufferWidth pixels. Each pixel is made up of colour channels. If we are dealing with a 32 bit buffer then there are 4 bytes per pixel. This means the length of one row in the buffer is 4 * bufferWidth bytes. We can use this fact to advance to any position in the buffer.

Given that each row is stride bytes wide we can calculate the offset to an arbitrary position in the buffer using

int offset = (x + y *bufferWidth) * bytesPerPixel;

Note: sometimes a buffer has padding at the end of each row (see the Pitch / Stride notes for more details). If this is the case and bufferWidth * bytesPerPixel does not equal the Pitch then this will need taking into account when calculating the offset. If there is no padding in your buffer then stride simply equals bufferWidth * bytesPerPixel. With a pitch value:

int offset = x * bytesPerPixel + y * pitch;

Once we have the offset we can position our pointer to the start of the pixel data.

BYTE *pnter = buffer + offset;

Given buffer is a pointer to the start of the memory buffer (top left pixel if buffer is a screen).

Packing the Colour

If our buffer has bytesPerPixel equalling 4 (32 bits) then it is common to create a DWORD type to hold a pixel colour: For other formats see Colour Formats.

typedef unsigned long DWORD;

If we are using a 32 bit colour format in the order Alpha, Red, Green, Blue we need to shift these byte values into the DWORD using bitwise operators. Note that I am using alpha here, however for a screen alpha does not exist it is purely a padded value but alpha can be used for texture buffers.

// Pack colour into a 32 bit variable, 4 bytes or 32 bits laid out like: 0xAARRGGBB
DWORD c = (a << 24 | r << 16 | g << 8 | b );

Copying the colour

Copying the colour into the buffer is now simply done using a fast memcpy: