String.Format for Hex

后端 未结 5 1446
星月不相逢
星月不相逢 2020-12-14 05:52

With below code, the colorsting always gives #DDDD. Green, Red and Space values int he How to fix this?

string colorstring;
int Blue = 13;
int Green = 0;
int         


        
5条回答
  •  佛祖请我去吃肉
    2020-12-14 06:43

    Translate composed UInt32 color Value to CSS in .NET

    I know the question applies to 3 input values (red green blue). But there may be the situation where you already have a composed 32bit Value. It looks like you want to send the data to some HTML CSS renderer (because of the #HEX format). Actually CSS wants you to print 6 or at least 3 zero filled hex digits here. so #{0:X06} or #{0:X03} would be required. Due to some strange behaviour, this always prints 8 digits instead of 6.

    Solve this by:

    String.Format("#{0:X02}{1:X02}{2:X02}", (Value & 0x00FF0000) >> 16, (Value & 0x0000FF00) >> 8, (Value & 0x000000FF) >> 0)
    

提交回复
热议问题