【问题标题】:How to do Bitwise AND(&) on CString values in MFC(VC++)?如何在 MFC(VC++)中对 CString 值进行按位与(&)?
【发布时间】:2011-05-13 17:42:12
【问题描述】:

嗨,

如何在 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' 没有定义此运算符或转换为预定义运算符可接受的类型”

【问题讨论】:

    标签: visual-c++ mfc


    【解决方案1】:

    你没有。在两个字符串上执行按位与并没有多大意义。您需要获取 IP 地址字符串的二进制表示,然后您可以对它们执行任何按位操作。这可以通过首先 obtaining a const char* from a CString 然后将其传递给 the inet_addr() function 来轻松完成。

    基于您的代码 sn-p 的(简单)示例。

    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 &lt;windows.h&gt; 通常就足够了,因为它包含 winsock.h)并链接到 WinSock 库(wsock32.lib,如果您包含 winsock.h)。

    【讨论】:

    • @In silico:请提供一些样本。
    • @Swapnil Gupta:根据inet_addr() 文档和我链接的 Stack Overflow 问题/答案应该很容易弄清楚。但是,我添加了几行。
    • @In silico : 使用这种方法我可以找出两个 IP 地址是否在同一个网络中?
    • @In silico:那么 gud 的方法是什么?
    猜你喜欢
    • 2011-05-17
    • 2019-10-19
    • 2011-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-15
    • 2015-10-29
    • 2013-02-03
    相关资源
    最近更新 更多