2010-11-22 114 views
0

HI,如何在MFC(VC++)中對CString值進行按位與(&)操作?

如何在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值? 它給出的錯誤爲''CString'沒有定義這個運算符或轉換爲預定義運算符可接受的類型「

回答

5

您不需要。在兩個字符串上逐位進行並行處理並沒有多大意義。您需要獲取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)。

+0

@In silico:請提供一些示例。 – 2010-11-22 09:44:20

+0

@Swapnil Gupta:根據'inet_addr()'文檔和我鏈接的堆棧溢出問題/答案應該很容易找出結論。但是,我已經添加了幾行。 – 2010-11-22 09:57:45

+0

@In silico:使用這種方法,我可以找出兩個IP地址是否在同一個網絡中? – 2010-11-22 10:09:10