Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert MS Access Color Code to Hex in C#

Is there a method to convert MS Access Color codes to Hex in C#?

e.g.

 - (white) 16777215 -> #FFFFFF
 - (black) 0        -> #000000
 - (blue)  16711680 -> #0000FF

Here are some reference tables I found on stackoverflow

  • http://www.endprod.com/colors/invcol.htm
  • http://cloford.com/resources/colours/500col.htm
like image 793
Ernest Avatar asked Apr 24 '13 17:04

Ernest


2 Answers

You can convert to hex like so:

 string hexValue = "#" + 16777215.ToString("X");

Or wrap it up in a method:

 public static string AccessToHex(int colorCode) {
      return "#" + colorCode.ToString("X");
 }
like image 53
Jeffrey Kevin Pry Avatar answered Oct 18 '22 09:10

Jeffrey Kevin Pry


You need to convert the value to hexadecimal, then flip the first two digits with the last two. For example, converting the raw value of 16711680 for blue gives an hex value of FF0000. However, the value for blue is 0000FF; a swap is required (So yes, the other answer is wrong...)

The value is also padded to always have the 6 required digits.

string rawHex = msAccessColorCode.ToString("X").PadLeft(6, '0');
string hexColorCode = "#" + rawHex.Substring(4, 2) + rawHex.Substring(2, 2) + rawHex.Substring(0, 2);

To do the reverse (hex -> Ms Acces), simply do the steps the other way around. Strip the extra # character, flip back the first/last two values and convert that number from base 16 to base 10.

string input = "#0000FF";
string hexColorCode = input.TrimStart('#');
string rawHex = hexColorCode.Substring(4, 2) + hexColorCode.Substring(2, 2) + hexColorCode.Substring(0, 2);
string result = Convert.ToInt32(rawHex, 16).ToString(); //16711680

Please note that Intew.Max is set to 0x7FFFFFFF (And our color codes cap at 0xFFFFFF), so it's completely safe to use Convert.ToInt32 here instead of Int64.

like image 32
Pierre-Luc Pineault Avatar answered Oct 18 '22 08:10

Pierre-Luc Pineault