code: private static int toAnsi(int red, int green, int blue)
      {
          // rescale to 0-5 range
          red = red * 6 / 256;
          green = green * 6 / 256;
          blue = blue * 6 / 256;
  
          return 16 + red * 36 + green * 6 + blue;
      }
docs: Convert the given color (rgb or system) to an ansi-compatible index (for use with ESC[38;5;<value>m)