提取INT N个最显著非零位在C ++中没有循环 [英] Extract n most significant non-zero bits from int in C++ without loops

查看:237
本文介绍了提取INT N个最显著非零位在C ++中没有循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从在C ++中的整数提取所述n最显著比特和那些n位转换为整数。

I want to extract the n most significant bits from an integer in C++ and convert those n bits to an integer.

例如

int a=1200;
// its binary representation within 32 bit word-size is
// 00000000000000000000010010110000

现在我想提取从重新presentation 4个最显著的数字,即1111

Now I want to extract the 4 most significant digits from that representation, i.e. 1111

00000000000000000000010010110000
                     ^^^^

和再次将其转换为一个整数(十进制1001 = 9)。

and convert them again to an integer (1001 in decimal = 9).

怎么可能用一个简单的C ++函数没有循环?

How is possible with a simple c++ function without loops?

推荐答案

一些处理器有一个指令来计算一个整数的领先二进制零,有的编译器有instrinsics让您使用该指令。例如,使用GCC

Some processors have an instruction to count the leading binary zeros of an integer, and some compilers have instrinsics to allow you to use that instruction. For example, using GCC:

uint32_t significant_bits(uint32_t value, unsigned bits) {
    unsigned leading_zeros = __builtin_clz(value);
    unsigned highest_bit = 32 - leading_zeros;
    unsigned lowest_bit = highest_bit - bits;

    return value >> lowest_bit;
}

为了简单起见,我离开了那支票位的请求数量是可用的。对于微软的编译器,内部被称为 __ lzcnt

如果你的编译器不提供内在的,并且你的处理器没有合适的指令,那么人们很快算零方式是用二进制搜索:

If your compiler doesn't provide that intrinsic, and you processor doesn't have a suitable instruction, then one way to count the zeros quickly is with a binary search:

unsigned leading_zeros(int32_t value) {
    unsigned count = 0;
    if ((value & 0xffff0000u) == 0) {
        count += 16;
        value <<= 16;
    }
    if ((value & 0xff000000u) == 0) {
        count += 8;
        value <<= 8;
    }
    if ((value & 0xf0000000u) == 0) {
        count += 4;
        value <<= 4;
    }
    if ((value & 0xc0000000u) == 0) {
        count += 2;
        value <<= 2;
    }
    if ((value & 0x80000000u) == 0) {
        count += 1;
    }
    return count;
}

这篇关于提取INT N个最显著非零位在C ++中没有循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆