union、struct、位域的组合定义示例

//#define USE_LOCAL_MESHCODE
const uint32 NullMeshCode = 0xFFFFFFFF;
union LocalMeshCode
{
	struct
	{
		uint32	H:4;
		uint32	G:4;
		uint32	F:4;
		uint32	E:4;
		uint32	D:4;
		uint32	C:4;
		uint32	B:4;
		uint32	A:4;
	};
	uint32 mc;
	LocalMeshCode &operator=(const uint32 t){mc=t; return *this;}
	LocalMeshCode(const uint32 t):mc(t){}
	std::string to_str(){std::string s;format(s, "%08X", mc);return s;}
	LocalMeshCode(){}
	~LocalMeshCode(){}
};
union GlobleMeshCode
{
	struct
	{
		uint32	F:4;
		uint32	E:4;
		uint32	D:3;
		uint32	C:3;
		int32	B:10;
		int32	A:8;
	};
	uint32 mc;
	GlobleMeshCode &operator=(const uint32 t){mc=t; return *this;}
	GlobleMeshCode(const uint32 t):mc(t){}
	std::string to_str(){std::string s;format(s, "%08X", mc);return s;}
	GlobleMeshCode(){}
	~GlobleMeshCode(){}
};
#ifdef USE_LOCAL_MESHCODE
typedef LocalMeshCode	MeshCode;
#else
typedef GlobleMeshCode	MeshCode;
#endif

format是自定义的小函数,如下

namespace std
{
	int format(std::string &s, const char* szFormat, ...)
	{
		enum { MAX_CHARS = 0x1000 };
		char buffer[MAX_CHARS];
		va_list argList;
		va_start(argList,szFormat);
#ifdef _UNICODE
		int ret = vswprintf(buffer,szFormat,argList);
#else
		int ret = vsprintf(buffer,szFormat,argList);
#endif
		va_end(argList);
		s = buffer;
		return ret;
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_43172531/article/details/103764627