开发者

How to do Bitwise AND(&) on CString values in MFC(VC++)?

HI,

How to do Bitwise AND(&) on CString values in MFC(VC++)? Example :

CString NASServerIP = "172.24.15.25";
CString  SystemIP = " 142.25.24.85";
CString strSubnetMask = "255.255.255.0";

int result1 = NASServerIP & strSubnetMask开发者_StackOverflow;
int result2 = SystemIP & strSubnetMask;

if(result1==result2)
{
    cout << "Both in Same network";
}
else
{
    cout << "not in same network";
}

How i can do bitwise AND on CString values ? Its giving error as "'CString' does not define this operator or a conversion to a type acceptable to the predefined operator"


You don't. Peforming a bitwise-AND on two strings doesn't make a lot of sense. You need to obtain binary representations of the IP address strings, then you can perform whatever bitwise operations on them. This can be easily done by first obtaining a const char* from a CString then passing it to the inet_addr() function.

A (simple) example based on your code snippet.

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";
}

The bytes in the unsigned longs are "reversed" from the string representation. For example, if your IP address string is 192.168.1.1, the resulting binary from inet_addr would be 0x0101a8c0, where:

  • 0x01 = 1
  • 0x01 = 1
  • 0xa8 = 168
  • 0xc0 = 192

This shouldn't affect your bitwise operations, however.

You of course need to include the WinSock header (#include <windows.h> is usually sufficient, since it includes winsock.h) and link against the WinSock library (wsock32.lib if you're including winsock.h).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜