简体   繁体   中英

Converting this type color value to ARGB

If I inputted 0xffffffff then the output must be: A: 255 R: 255 G: 255 B: 255

I can't find any tutorials for converthing this. Thanks!

You can use the Color structure ( From the .NET System.Drawing assembly) to parse this:

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

which produces the following output:

Alpha: 170
Red: 51
Green: 101
Blue: 57

shifting and masking.

(although some prefer using a / 256 for the shift and a % 256 for the mask )

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM