Conversion between RGB color values and integer values in C #

Source: Internet
Author: User

When I looked at a database of the previous system over the past two days, I found that there was a color field, which obviously stored the color. However, the field type is integer, And the stored value is a long string of numbers. For a moment, I ran to ask the manager how to convert the number into three values: R, G, and B? The manager said that you do not know the RGB function? Oh, remember. A friend developed with VB should know this function. Specifically, it is a macro. In msdn6, find its definition:
# Define RGB (R, G, B) (DWORD) (byte) (R) | \ (Word) (g) <8 )) | \ (DWORD) (byte) (B) <16 )))

Maybe you are not good at computer basics like me, and it is a bit dizzy to see these pile of things. Then, let's take a look at the formula with the same effect as below:
RGB = R + G * 256 + B * 256*256

C # does not have the RGB function, but I know the principle and can write it out immediately.
Method 1: Stupid, inefficient, but easy to understand.

Int RGB =   202   +   69   *   256   +   137   *   256   *   256 ;
Int B = RGB / ( 256   *   256 );
Int G = (RGB - B *   256   *   256 ) /   256 ;
Int R = (RGB - B *   256   *   256   - G *   256 );

Method 2: shift is the most efficient method. However, according to msdn, uint, ushort, and Other types do not comply with CLs, and I don't know what the problem will be.
Uint Parsergb (color)
{
Return ( Uint )((( Uint ) Color. B <   16 ) | ( Ushort )((( Ushort ) Color. g <   8 ) | Color. R ));
}

Color RGB ( Int Color)
{
Int R =   0xff   & Color;
Int G =   0xff00   & Color;
G >>=   8 ;
Int B =   0xff0000   & Color;
B >>=   16 ;
Return Color. fromargb (R, G, B );
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.