C# 从 RGB 整数转换为十六进制

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13354892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:18:07  来源:igfitidea点击:

Converting from RGB ints to Hex

c#bitmapbit-shift

提问by Toadums

What I have is R:255 G:181 B:178, and I am working in C# (for WP8, to be more specific)

我拥有的是 R:255 G:181 B:178,我正在使用 C#(对于 WP8,更具体地说)

I would like to convert this to a hex number to use as a color (to set the pixel color of a WriteableBitmap). What I am doing is the following:

我想将其转换为十六进制数以用作颜色(设置 WriteableBitmap 的像素颜色)。我正在做的是以下内容:

int hex = (255 << 24) | ((byte)R << 16) | ((byte)G << 8) | ((Byte)B<<0);

But when I do this, I just get blue.

但是当我这样做时,我只会变蓝。

Any ideas what I am doing wrong?

任何想法我做错了什么?

Also, to undo this, to check the RGB values, I am going:

另外,要撤消此操作,检查 RGB 值,我将:

int r = ((byte)(hex >> 16)); // = 0
int g = ((byte)(hex >> 8)); // = 0
int b = ((byte)(hex >> 0)); // = 255

采纳答案by NoPyGod

Try the below:

试试下面的:

using System.Drawing;
Color myColor = Color.FromArgb(255, 181, 178);
string hex = myColor.R.ToString("X2") + myColor.G.ToString("X2") + myColor.B.ToString("X2");

回答by Andreas

You can use a shorter string format to avoid string concatenations.

您可以使用较短的字符串格式来避免字符串连接。

string.Format("{0:X2}{1:X2}{2:X2}", r, g, b)

回答by huysentruitw

Using string interpolation, this can be written as:

使用字符串插值,这可以写成:

$"{r:X2}{g:X2}{b:X2}"

回答by Nelson Martins

Greetings fellow humans,

问候人类同胞,

//Red Value
int integerRedValue = 0;
//Green Value
int integerGreenValue = 0;
//Blue Value
int integerBlueValue  = 0;

string hexValue = integerRedValue.ToString("X2") + integerGreenValue.ToString("X2") + integerBlueValue.ToString("X2");