如何从 24 位十六进制中获取 RGB 值(没有 .NET Framework)

How to get RGB values from 24-bit Hex (Without .NET Framework)

我正在用 C# 做一些图形,我需要将 6 位 rgb 十六进制数(例如 0xaabbcc (rr gg bb))转换为 3 个 RGB 值。我不想使用 Color。我不是为 Windows 开发,所以我不想使用 Microsoft.CSharp 库。即使有一些方法让我不太喜欢 .NET 框架,因为所有花哨的绒毛,我更喜欢制作自己的 class 库等。

我能够将 3 个 RGB 值转换为一个十六进制数,但我不知道如何做相反的事情。

private static long MakeRgb(byte red, byte green, byte blue)
{
    return ((red*0x10000) + (green*0x100) + blue);   
}

这里有我的原始转换代码。

有人知道将 6 位十六进制数分成 3 个单独字节的好方法吗?

编辑:

使用.NET框架,使用Mono,我不[=30] =] 可以访问 System.Drawing.Color.

不应将其标记为重复,因为它与 .NET 无关。

适用于大多数语言的老式方式:

long color = 0xaabbcc;

byte red = (byte)((color >> 16) & 0xff);
byte green = (byte)((color >> 8) & 0xff);
byte blue = (byte)(color & 0xff);

您可以使用位掩码

private static long MakeRgb(byte red, byte green, byte blue)
{
    return ((red*0x10000) + (green*0x100) + blue);   
}

private static byte GetRed(long color)
{
    return (byte)((color & 0xFF0000) / 0x10000);
}

private static byte GetGreen(long color)
{
    return (byte)((color & 0x00FF00) / 0x100);
}

private static byte GetBlue(long color)
{
    return (byte)((color & 0x0000FF));
}

long color = MakeRgb(23, 24, 25);

byte red = GetRed(color);
byte green = GetGreen(color);
byte blue = GetBlue(color);

System.Drawing.ColorMicrosoft.CSharp 都可以在 Mono 上使用(如果您不使用 .NET,我假设您正在使用它)

无论如何, 已经是一个很好的答案,但如果您真的不打算使用 System.Drawing.Color,那么您可能应该编写自己的 class。

class MyColorClass
{
     public byte Red { get; set; }
     public byte Green { get; set; }
     public byte Blue { get; set; }

     public MyColorClass(long color)
     {
         Red = (byte)((color >> 16) & 0xff);
         Green = (byte)((color >> 8) & 0xff);
         Blue = (byte)(color & 0xff);
     }

     public override string ToString()
     {
         return string.Format("R: {0} G: {1} B: {2}", Red, Green, Blue);
     }
 }

 static void Main(string[] args)
 {
     long lcolor = MakeRgb(50, 100, 150);
     MyColorClass color = new MyColorClass(lcolor);
     Console.WriteLine(color);
 }