14

I took the following code from HexConverter - Unify Community Wiki

string hex = color.r.ToString("X2") + color.g.ToString("X2") + color.b.ToString("X2");

This gives me the exception:

FormatException: The specified format 'X2' is invalid

I tried then to use "D" but even this threw an error. The only thing working is "F for formatting float numbers.

Go to declaration reveals mscorlib.dll/System/Single.ToString (string) in assembly browser - sounds good so far.

Googling for monodevelop string format hex or similar search strings did not show anything interesting regarding restrictions in MonoDevelop.

So is there anything to prepare, initialise, ... before I can get a simple hex value Conversion?

[Update] Color is a struct in Unity:

public struct Color
{
    public float r;
    public float g;
    public float b;
    // ...

Taking dtb's answer I finally got it working using:

    int r = (int)(color.r * 256);
    int g = (int)(color.g * 256);
    int b = (int)(color.b * 256);
    string hex = string.Format ("{0:X2}{1:X2}{2:X2}", r, g, b);

So I missed the fact that Color defines its components as float instead of int and the integral types thing dtb has mentioned.

[Update-2] More elegant solution:

Color32 color32 = color;
string hex = color32.r.ToString ("X2") + color32.g.ToString ("X2") + color32.b.ToString ("X2");
Kay
  • 12,918
  • 4
  • 55
  • 77
  • 1
    Can we see your declaration of color? or is it directly form the wiki? – emd Jun 05 '13 at 17:16
  • As a simple test, I used `System.Drawing.Color.White.R.ToString("X2")` and received as String return `FF`. So yes, what is "color" in your example? – DonBoitnott Jun 05 '13 at 17:21
  • @emd It's Unity's `Color` struct. In the wiki they use `Color32` which is different. This was the point in combination with dtb's statement about type `Single`. Thanks :-) – Kay Jun 05 '13 at 18:01

1 Answers1

16

From MSDN:

The hexadecimal ("X") format specifier converts a number to a string of hexadecimal digits. The case of the format specifier indicates whether to use uppercase or lowercase characters for hexadecimal digits that are greater than 9. For example, use "X" to produce "ABCDEF", and "x" to produce "abcdef". This format is supported only for integral types.

Single is a floating-point type, not an integral type.

Use an Int32:

int value = 10;
string result = value.ToString("X2");
// result == "0A"
dtb
  • 213,145
  • 36
  • 401
  • 431