如何从24位hex获取RGB值(不使用.NET Framework)

我在C#中做一些图形,我需要将一个6位rgbhex(如0xaabbcc(rr gg bb))转换为3个RGB值。 我不想使用Color 。 我不是在为Windows开发,所以我不想使用Microsoft.CSharp库。 即使有一些方法,由于所有花哨的绒毛,我不太喜欢.NET框架,我更喜欢创建自己的类库等。

我能够将3个RGB值转换为单个hex数,但我不知道如何做相反的事情。

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

我有原始转换的代码。

有人知道将6位hex数分成3个独立字节的好方法吗?

编辑:

没有使用.NET框架, 没有使用Mono,我也无法访问System.Drawing.Color。

这不应该被标记为重复,因为它与.NET无关。

旧式时尚方式,适用于大多数语言:

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

你可以使用bitmasking

 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 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); }