一些用法一一利用Mask记录一些开关选项

来源:互联网 发布:国家顶级域名 编辑:程序博客网 时间:2024/05/16 14:05

        在一些项目使用中,我们经常需要确认项目中某些选择项是否勾选/有效,有时会采用数组的形式进行记录,但是读取的时候需要对数组进行遍历,记录前后状态,这里,我们可以采用Mask的机制来完成,此种用法主要用到了十六进制计数方法,便于按位求非(剔除)及按位求与(增加)操作。

下面根据示例说明:

#define  MAX_SLOT 4static unsigned longgulMask[]={0x00000001,0x00000002,0x00000004,0x00000008,0x00000010,0x00000020,0x00000040,0x00000080,0x00000100,0x00000200,0x00000400,0x00000800,0x00001000,0x00002000,0x00004000,0x00008000,0x00010000,0x00020000,0x00040000,0x00080000,0x00100000,0x00200000,0x00400000,0x00800000,0x01000000,0x02000000,0x04000000,0x08000000,0x10000000,0x20000000,0x40000000,0x80000000,};
#include <Windows.h>#include <stdio.h>#include <iostream>#include "MaskTest.h"using namespace std;int g_bEnable[MAX_SLOT] = {false};int main(){char szDir[MAX_PATH]="";int  iMask = 0;GetCurrentDirectory(sizeof(szDir),szDir);char szIniPath[MAX_PATH]="";sprintf(szIniPath,"%s\\Config.ini",szDir);iMask = GetPrivateProfileInt("SlotEnable","SlotMask",1,szIniPath);//根据配置文件中的SlotMask值来确定哪些Slot是Enable的for (int index=0;index<MAX_SLOT;index++){if ((iMask & gulMask[index]) == gulMask[index]){g_bEnable[index] = true;cout<<"Slot "<<index<<"Enable"<<endl;}}int i = 0;iMask = 0;//改变Slot的Enable值,然后重新存入到配置文件中去for (int index=0;index<MAX_SLOT;index++){cout<<"Slot: "<<index<<"Enable or not?"<<endl;cin>>i;g_bEnable[index] = i;if (g_bEnable[index]){iMask += gulMask[index];}}char czMask[10]="";itoa(iMask,czMask,10);WritePrivateProfileString("SlotEnable","SlotMask",czMask,szIniPath);system("pause");return 0;}

原创粉丝点击