Search code examples
cvga

VGA Programming in C: Getting the x, y coordinates from and offset


I'm programming the for the 256 color VGA in C. The screen size I have is 320*200 so based on that assumption I made my plot pixel function as follows:

void plot_pixel(int x, int y, byte color){
  int offset;
  offset = (y<<8) + (y<<6) + x;
  VGA[offset]=color;
}

I always translate the x, y coordinates of my screen to an offset of video memory. What I'm struggling to achieve is to do the opposite. I would like to send a function the video offset and return to me an array with the 2 integers corresponding to the x and y coordinates:

get_xy(int offset){
   ...
}

However, I still cannot find a way to translate a single number into two values.

Can anyone help me achieve this?


Solution

  • Simple reverse the math. Best to use unsigned types.

    y = offset/((1<<8) + (1<<6)); 
    x = offset%((1<<8) + (1<<6));