如果我输入0xffffffff,那么输出必须是: 答:255 R:255 G:255 B:255
我找不到任何转换此教程的教程。谢谢!
答案 0 :(得分:3)
您可以使用Color
结构(来自.NET System.Drawing
程序集)来解析它:
using System;
using System.Drawing;
void Main()
{
var c = Color.FromArgb(unchecked((int)0xaa336539));
Console.WriteLine("Alpha: {0}", c.A);
Console.WriteLine("Red: {0}", c.R);
Console.WriteLine("Green: {0}", c.G);
Console.WriteLine("Blue: {0}", c.B);
}
产生以下输出:
Alpha: 170
Red: 51
Green: 101
Blue: 57
答案 1 :(得分:2)
转移和掩蔽。
(虽然有些人更喜欢使用/ 256
进行转换,而使用% 256
进行转换
unsigned long x = 0xaa336539;
// Note the LSB to MSB order
//mask
unsigned char b = x & 0xff;
//shift
x >>= 8;
//mask
unsigned char g = x & 0xff;
//shift
x >>= 8;
//mask
unsigned char r = x & 0xff;
//shift
x >>= 8;
//mask
unsigned char a = x & 0xff;
// Technically, just saving it into an 8 bit wide container is the same as the masking, although some compilers might warn you
答案 2 :(得分:1)
// Original input
var input = "0xaa336539";
// Gets aa336539
var inputRemovePrefix = input.Substring(2);
// Converts to a long
var numberConversion = long.Parse(inputRemovePrefix, System.Globalization.NumberStyles.HexNumber);
// Converts to 6 character hex string so the next operation will always work
var convertedInput = numberConversion.ToString("X6");
var aVal = int.Parse(convertedInput.Substring(0,2), System.Globalization.NumberStyles.HexNumber);
var rVal = int.Parse(convertedInput.Substring(2,2), System.Globalization.NumberStyles.HexNumber);
var gVal = int.Parse(convertedInput.Substring(4,2), System.Globalization.NumberStyles.HexNumber);
var bVal = int.Parse(convertedInput.Substring(6,2), System.Globalization.NumberStyles.HexNumber);
// Prints result
Console.WriteLine($"A: {aVal} R: {rVal} G: {gVal} B: {bVal}");