嗨,
如何在MFC(VC++)中对CString值进行位与(&)运算?示例:
CString NASServerIP = "172.24.15.25";
CString SystemIP = " 142.25.24.85";
CString strSubnetMask = "255.255.255.0";
int result1 = NASServerIP & strSubnetMask;
int result2 = SystemIP & strSubnetMask;
if(result1==result2)
{
cout << "Both in Same network";
}
else
{
cout << "not in same network";
}如何对CString值执行按位AND运算?它给出的错误是"'CString‘没有定义这个运算符,也没有转换为预定义运算符可以接受的类型“
发布于 2010-11-22 17:35:56
你不需要。在两个字符串上执行按位AND没有多大意义。您需要获取IP地址字符串的二进制表示形式,然后才能对其执行任何按位操作。这可以通过先obtaining a const char* from a CString,然后将其传递给the inet_addr() function来轻松完成。
基于您的代码片段的(简单)示例。
CString NASServerIP = "172.24.15.25";
CString SystemIP = " 142.25.24.85";
CString strSubnetMask = "255.255.255.0";
// CStrings can be casted into LPCSTRs (assuming the CStrings are not Unicode)
unsigned long NASServerIPBin = inet_addr((LPCSTR)NASServerIP);
unsigned long SystemIPBin = inet_addr((LPCSTR)SystemIP);
unsigned long strSubnetMaskBin = inet_addr((LPCSTR)strSubnetMask);
// Now, do whatever is needed on the unsigned longs.
int result1 = NASServerIPBin & strSubnetMaskBin;
int result2 = SystemIPBin & strSubnetMaskBin;
if(result1==result2)
{
cout << "Both in Same network";
}
else
{
cout << "Not in same network";
}unsigned longs中的字节与字符串表示形式“颠倒”。例如,如果您的IP地址字符串是192.168.1.1,则从inet_addr得到的二进制文件将是0x0101a8c0,其中:
0x01 = 10x01 = 10xa8 = 1680xc0 = 192然而,这应该不会影响您的按位操作。
当然,您需要包含WinSock标头(#include <windows.h>通常就足够了,因为它包含winsock.h)和针对WinSock库的链接(如果包含winsock.h,则为wsock32.lib)。
https://stackoverflow.com/questions/4243946
复制相似问题