几年前我写了这段代码:
int CAssignSelectedColumnDlg::RegistryIntFromData(int iColumnIndex, int iCustomIndex, BOOL bAvoidConflicts, int iNumMeetings)
{
WORD wLowWord = MAKEWORD(iColumnIndex, iCustomIndex);
WORD wHighWord = MAKEWORD(bAvoidConflicts ? 1 : 0, iNumMeetings);
return (int)MAKEWPARAM(wLowWord, wHighWord);
}
现在我重温这段代码。我需要引入一个BOOL
0/1的第5个数字。这可能吗?
答案 0 :(得分:1)
请注意,iColumnIndex
,iCustomIndex
和iNumMeetings
不能超过255
,而应为BYTE
。您可以在BOOL
lobyte
中添加更多hiword
个值。返回值应为unsigned int
。为了向后兼容,您应该将返回值保留为int
。
int foo(int iColumnIndex, int iCustomIndex,
BOOL bAvoidConflicts, int iNumMeetings, BOOL bFifth)
{
bAvoidConflicts = !!bAvoidConflicts;
bFifth = !!bFifth;
WORD loword = MAKEWORD(iColumnIndex, iCustomIndex);
BYTE lobyte = (BYTE)(bAvoidConflicts << 0) | (BYTE)(bFifth << 1);
BYTE hibyte = (BYTE)iNumMeetings;
WORD hiword = MAKEWORD(lobyte, hibyte);
return (int)MAKEWPARAM(loword, hiword);
}
并检查值:
unsigned int res = foo(x1, x2, x3, x4, x5);
WORD loword = LOWORD(res);
WORD hiword = HIWORD(res);
BYTE iColumnIndex = LOBYTE(loword);
BYTE iCustomIndex = HIBYTE(loword);
BYTE lobyte = LOBYTE(hiword);
BYTE iNumMeetings = HIBYTE(hiword);
BOOL bAvoidConflicts = !!(lobyte & 1);
BOOL bFifth = !!(lobyte & 2);
if(x1 != iColumnIndex) printf("error 1\n");
if(x2 != iCustomIndex) printf("error 2\n");
if(x3 != bAvoidConflicts) printf("error 3\n");
if(x4 != iNumMeetings) printf("error 4\n");
if(x5 != bFifth) printf("error 5\n");
当然,如果你只使用一个结构并将值存储为int
,bool
等,会更容易。
这是添加更多位的不同版本,或强制指示新版本的位。
这些名字现在令人困惑。 bFifth
是第五个参数,是第二个位(bit1 << 1)
bit2
(第三位!)设置为1
int foo(int iColumnIndex, int iCustomIndex,
BOOL bAvoidConflicts, int iNumMeetings, BOOL bFifth)
{
bAvoidConflicts = !!bAvoidConflicts;
bFifth = !!bFifth;
WORD loword = MAKEWORD(iColumnIndex, iCustomIndex);
BOOL bit0 = bAvoidConflicts;
BOOL bit1 = bFifth;
BOOL bit2 = 1; //<-- always 1 to indicate new version
BYTE lobyte = 0;
lobyte |= (BYTE)(bit0 << 0);
lobyte |= (BYTE)(bit1 << 1);
lobyte |= (BYTE)(bit2 << 2);
//lobyte |= (BYTE)(bit3 << 3);
//lobyte |= (BYTE)(bit4 << 4);
//lobyte |= (BYTE)(bit5 << 5);
//lobyte |= (BYTE)(bit6 << 6);
//lobyte |= (BYTE)(bit7 << 7);
WORD hiword = MAKEWORD(lobyte, iNumMeetings);
return (int)MAKEWPARAM(loword, hiword);
}
可以像以前一样检查
int res = foo(255, 254, 1, 253, 1);
WORD loword = LOWORD(res);
WORD hiword = HIWORD(res);
BYTE iColumnIndex = LOBYTE(loword);
BYTE iCustomIndex = HIBYTE(loword);
BYTE iNumMeetings = HIBYTE(hiword);
BYTE lobyte = LOBYTE(hiword);
BOOL b0 = !!(lobyte & 1); //bAvoidConflicts
BOOL b1 = !!(lobyte & 2); //bFifth
BOOL b2 = !!(lobyte & 4); //version check
BOOL b3 = !!(lobyte & 8); //not used
BOOL b4 = !!(lobyte & 16); //not used
BOOL b5 = !!(lobyte & 32); //not used
BOOL b6 = !!(lobyte & 64); //not used
BOOL b7 = !!(lobyte & 128);//not used