How to get RGB values from 24-bit Hex (Without .NE

2020-05-09 19:08发布

I am doing some graphics in C# and I need to convert a 6-digit rgb hexadecimal such as 0xaabbcc (rr gg bb) into 3 RGB values. I don't want to use Color. I am not developing for Windows so I don't want to use the Microsoft.CSharp library. Even if there is some way around that I'm not very fond of the .NET framework due to all the fancy fluff, I prefer to make my own class libraries and such.

I was able to convert 3 RGB values into a single Hex number but I don't know how to do the opposite.

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

There is my code for the original conversion.

Anyone know a good way to separate a 6 digit hex number into 3 separate bytes?

EDIT:

I am not using the .NET framework, not using Mono, and I do not have access to System.Drawing.Color.

This should not be marked as a duplicate because it has nothing to do with .NET.

标签: c# colors hex rgb
3条回答
Anthone
2楼-- · 2020-05-09 19:09

You could use 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);
查看更多
爷的心禁止访问
3楼-- · 2020-05-09 19:18

Both System.Drawing.Color and Microsoft.CSharp are available on Mono (which I assume you're using if you're not using .NET)

In any case, this was already a good answer, but if you're really not going to use System.Drawing.Color, then you should probably write your own 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);
 }
查看更多
闹够了就滚
4楼-- · 2020-05-09 19:27

Old fashion way that'll work in most languages:

long color = 0xaabbcc;

byte red = (byte)((color >> 16) & 0xff);
byte green = (byte)((color >> 8) & 0xff);
byte blue = (byte)(color & 0xff);
查看更多
登录 后发表回答