Click here to Skip to main content
15,881,172 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hey Guys,

i'm trying to convert a COLORREF to a Hex-CString and then back from Hex-CString into COLORREF and i've run into a small problem.

Here some Code for Converting from COLORREF to a CString (Hexadecimal):
This part isn't the problem.
C++
COLORREF crefColor = RGB(128,0,0);

DWORD dwR = GetRValue(crefColor);
DWORD dwG = GetGValue(crefColor);
DWORD dwB = GetBValue(crefColor);

CString sValue;
sValue.Format(_T("#%02X%02X%02X"), dwR, dwG, dwB);
ASSERT(sValue == _T("#800000")); // correct


Now the more annoying part.
Back from CString to COLORREF:

C++
CString sValue(_T("#800000"));
LPCTSTR pszTmp = sValue;
pszTmp++; // cut the #

COLORREF crefColor;
COLORREF crefColor2;
sscanf_s(pszTmp, "%x", &crefColor); // should return the same as strtol
crefColor2 = strtol(pszTmp, NULL, 16); // should return the same as sscanf_s
ASSERT(crefColor == crefColor2); // just to be sure

INT nR = GetRValue(crefColor);
ASSERT(nR == 128); // expected: 128; nR in reallity: 0

INT nG = GetGValue(crefColor);
ASSERT(nG == 0); // expected: 0; nG in reallity: 0

INT nB = GetBValue(crefColor);
ASSERT(nB == 0); // expected: 0; nB in realität: 128


Could anyone suggest me, why the RGB is reversed?
I mean, if i know this problem, i could fix it and simlpy reverse it back:
C++
crefColor = RGB(nB, nG, nR);


But i think the result should be in the right direction after sscanf_s / strtol
Hope anyone could explain me the reason for this and show me the mistake i've done with my code.

Thank you so much guys for helping me!
Posted
Comments
Sergey Alexandrovich Kryukov 16-Jul-14 2:47am    
This is easy enough, but why?
—SA
C3D1 16-Jul-14 2:53am    
I'm more interessted in the reason why the RGB-Value is reversed than in the solution.
Sergey Alexandrovich Kryukov 16-Jul-14 3:10am    
Hm. Look, you are calling RGB(g, b, r)...
Anyway, you did not answer my question, so why would I answer yours?
—SA
Jochen Arndt 16-Jul-14 2:56am    
Hint:
Have a look at the COLORREF entry in the MSDN (Windows GDI) and the implementations of the GetXValue macros.
C3D1 16-Jul-14 2:59am    
*facepalm* okay now i see where is the problem!
Thanks a lot!

1 solution

Big thanks to Jochen Arndt for his hint.

I updated my code for converting from Hexadecimal CString to COLORREF to this:
C++
CString sValue(_T("#800000"));
LPCTSTR pszTmp = sValue;
pszTmp++; // cut the #

LPTSTR pStop;
INT nTmp = _tcstol(pszTmp, &pStop, 16);
INT nR	= (nTmp & 0xFF0000) >> 16;
INT nG	= (nTmp & 0xFF00) >> 8;
INT nB	= (nTmp & 0xFF);

COLORREF crefColor = RGB(nR, nG, nB);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900