如何对MFC(VC ++)中的CString值进行按位AND(&)?

时间:2010-11-22 09:26:52

标签: visual-c++ mfc

HI,

如何对MFC(VC ++)中的CString值进行按位AND(&)? 示例:

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值进行操作? 它给出错误“'CString'没有定义此运算符或转换为预定义运算符可接受的类型”

1 个答案:

答案 0 :(得分:5)

你没有。在两个字符串上执行按位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 = 1
  • 0x01 = 1
  • 0xa8 = 168
  • 0xc0 = 192

但这不应影响您的按位操作。

您当然需要包含WinSock标头(#include <windows.h>通常已足够,因为它包含winsock.h)并且链接到WinSock库(wsock32.lib如果您包含{winsock.h 1}})。