计算两个给定整数的汉明距离——C++实现

本文介绍了两种计算两个整数汉明距离的方法。首先,通过位操作逐位检查两个整数异或结果中1的个数。其次,利用编译器内置的popcount函数直接计算异或结果中1的个数,实现更高效。适用于32位和64位整数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

常规实现,统计两个整数的异或结果中1的位数:

int hamming_distance(unsigned x, unsigned y)
{
    int dist = 0;
    
    // Count the number of bits set
    for (unsigned val = x ^ y; val > 0; val >>= 1)
    {
        // If A bit is set, so increment the count
        if (val & 1)
            dist++;
        // Clear (delete) val's lowest-order bit
    }

    // Return the number of differing bits
    return dist;
}

另外,还可以借助编译器内置的popcount来更高效地实现:

int hamming_distance(unsigned x, unsigned y)
{
    return __builtin_popcount(x ^ y);
}
//if your compiler supports 64-bit integers
int hamming_distance(unsigned long long x, unsigned long long y)
{
    return __builtin_popcountll(x ^ y);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值