Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting hexadecimal color to integer

This is my integer color in database : "8689404".

I change it to Color as following:

Color = ColorHelper.FromArgb(255,
        byte.Parse(Event.LABELCOLOR.Value.ToString("X8").Substring(6, 2), NumberStyles.HexNumber),
        byte.Parse(Event.LABELCOLOR.Value.ToString("X8").Substring(4, 2), NumberStyles.HexNumber),
        byte.Parse(Event.LABELCOLOR.Value.ToString("X8").Substring(2, 2), NumberStyles.HexNumber))

this gives me color string "#FFFC9684"

Now what problem is that i am unable to parse this color string back to integer, so that i can save it in database. What i have yet is:

byte A = byte.Parse(labelcolor.Color.TrimStart('#').Substring(0, 2), System.Globalization.NumberStyles.HexNumber);
byte B = byte.Parse(labelcolor.Color.TrimStart('#').Substring(6, 2), System.Globalization.NumberStyles.HexNumber);
byte G = byte.Parse(labelcolor.Color.TrimStart('#').Substring(4, 2), System.Globalization.NumberStyles.HexNumber);
byte R = byte.Parse(labelcolor.Color.TrimStart('#').Substring(2, 2), System.Globalization.NumberStyles.HexNumber);

this gives me:

A = 255
B = 132
G = 150
R = 252

These values are correct but i can't compare them with "8689404"

As per my findings:

B = 132 = 84 
G = 150 = 96
R = 252 = FC
A = 255 = FF

This is all what i have yet, how can i have integer for this color string. I am working in WinRT. Any help!!! thanks in advance

like image 915
A.T. Avatar asked Feb 16 '23 15:02

A.T.


1 Answers

This will produce the correct decimal value you want:

int decValue = int.Parse("8496FC", System.Globalization.NumberStyles.HexNumber);

As you can see the hex value used to produce the decimal value consists of the following colour components:

B (84) G (96) R (FC)

with the A component dropped.

This can be calculated by using a substring on your full hex colour like so:

string colour = labelcolor.Color.TrimStart('#');
string R = colour.Substring(2, 2);
string G = colour.Substring(4, 2);
string B = colour.Substring(6, 2);

Which you can then use like so:

int decValue = int.Parse(B + G + R, System.Globalization.NumberStyles.HexNumber);
//decValue = 8689404

Here is a working example

like image 113
musefan Avatar answered Feb 24 '23 07:02

musefan