本文介绍了如何将COLORREF转换为Hex-CString并返回COLORREF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿伙计,



我正在尝试将COLORREF转换为Hex-CString,然后从Hex-CString转换回COLORREF,我遇到了一个小问题。



这里有一些从COLORREF转换为CString(十六进制)的代码:

这部分不是问题。

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.

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





现在更烦人的部分。

从CString回到COLORREF:





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

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





有谁能建议我,为什么RGB会被颠倒?

我的意思是,如果我知道这个问题,我可以修复它并简单地将其反转:



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:

crefColor = RGB(nB, nG, nR);





但是我觉得结果应该是在sscanf_s / strtol之后正确的方向

希望有人能解释我原因为此,告诉我我的代码所犯的错误。



非常感谢你帮助我!



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!

推荐答案

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


这篇关于如何将COLORREF转换为Hex-CString并返回COLORREF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 16:49