With below code, the colorsting always gives #DDDD. Green, Red and Space values int he How to fix this?
string colorstring;
int Blue = 13;
int Green = 0;
int Red = 0;
int Space = 14;
colorstring = String.Format("#{0:X}{0:X}{0:X}{0:X}", Blue, Green, Red, Space);
This question is related to
c#
string
formatting
hex
If we have built in functions to convert your integer values to COLOR then why to worry.
string hexValue = string.Format("{0:X}", intColor);
Color brushes = System.Drawing.ColorTranslator.FromHtml("#"+hexValue);
More generally.
byte[] buf = new byte[] { 123, 2, 233 };
string s = String.Concat(buf.Select(b => b.ToString("X2")));
You can also pad the characters left by including a number following the X
, such as this: string.format("0x{0:X8}", string_to_modify)
, which yields "0x00000C20"
.
Translate composed UInt32 color Value
to CSS in .NET
I know the question applies to 3 input values (red
green
blue
). But there may be the situation where you already have a composed 32bit Value
. It looks like you want to send the data to some HTML CSS renderer (because of the #HEX format). Actually CSS wants you to print 6 or at least 3 zero filled hex digits here. so #{0:X06}
or #{0:X03}
would be required. Due to some strange behaviour, this always prints 8 digits instead of 6.
Solve this by:
String.Format("#{0:X02}{1:X02}{2:X02}", (Value & 0x00FF0000) >> 16, (Value & 0x0000FF00) >> 8, (Value & 0x000000FF) >> 0)
Source: Stackoverflow.com