将RGB int值转换为c#中前缀为0x的十六进制格式

本文关键字:前缀 0x 格式 十六进制 RGB int 转换 | 更新日期: 2023-09-27 18:25:24

我正在尝试使用以下代码将RGB值转换为c#中的十六进制格式:

int ColorValue = Color.FromName("mycolor").ToArgb();
string ColorHex = string.Format("{0:x6}", ColorValue);

colorHex值喜欢这种格式ffffff00,但我需要把它改成这样:0x0000。我该怎么做?

向致以最良好的问候

我对c#表单应用程序很陌生。

将RGB int值转换为c#中前缀为0x的十六进制格式

只需在格式字符串中添加0x部分:

// Local variable names to match normal conventions.
// Although Color doesn't have ToRgb, we can just mask off the top 8 bits,
// leaving RGB in the bottom 24 bits.
int colorValue = Color.FromName("mycolor").ToArgb() & 0xffffff;
string colorHex = string.Format("0x{0:x6}", colorValue);

如果您想要大写十六进制值而不是小写,请使用"0x{0:X6}"

如果你只想要定义颜色RGB部分的3个字节,你可以尝试这个

    Color c = Color.FromName("mycolor");
    int ColorValue = (c.R * 65536) + (c.G * 256) + c.B;
    string ColorHex = string.Format("0x{0:X6}", ColorValue);