tags:

views:

95

answers:

2

I have a bunch of Color objects (.Net). I want to convert them to Hex, which is simple enough with something like:

Dim clr As Color = Color.FromArgb(255, 0, 0)
Dim clrString = ColorTranslator.ToHtml(clr)

Is there a way in .Net or through RegEx (or some other way) that I can determine if Hex shorthand (like #F00) is available for the specified Color and then convert it to that? So for colors that can have a Hex shorthand, convert to that, otherwise, convert to Hex Pair #FF0000.

+3  A: 
^#([0-9A-F])\1([0-9A-F])\2([0-9A-F])\3$

This uses 3 back-references to check that each hex digit is followed by a copy. So anything with the pattern #xxyyzz (which can be converted to #xyz) matches.

Matthew Flaschen
Thanks Matthew. Unfortunately, this only gets me part of the way in that it works with `FF` and `00`. It doesn't provide a match for a color like Color.Olive, which is `#808000` and can be written as `#880` in hex shorthand.
Otaku
Did some more research, turns out that shorthand can only be written from hex pairs. Your code works great! I've also discovered that if the color value byte can by divided by 17 and return an integer (i.e. it's not a float), then it can be written shorthand. Don't know the math behind that, but it's cool.
Otaku
17 is 0x11. All the bytes with doubled hex digits are multiples of that.
Matthew Flaschen
+1  A: 

This link describes how the Shorthand Hex Notation works.

Shorthand Hex Notation

So, in theory, any implementation that will allow you to analyze a Hex RGB value and detect "duplicate double" character values should be able to reduce it to a Hex Shorthand.

Cheers

Dave White