【问题标题】:C - Get position of leftmost set bit from an 8 bit integer without loopsC - 从没有循环的 8 位整数中获取最左边的设置位的位置
【发布时间】:2019-03-31 07:12:26
【问题描述】:

我正在尝试制作一个程序,它打印出 C 中最左边 1 位的位置,但没有循环。

这是我目前收集到的:

#include<stdio.h>
int main() {
    unsigned int x, y;
    printf("Enter an integer: ");
    scanf("%d", &x);
    // Bit 
    x |= x >> 4;
    x |= x >> 2;
    x |= x >> 1;
    x ^= x >> 1;
    printf("\n%d", x);
    return 0;
}

这会将最左边的位打印为整数,但我无法将其转换为其最高设置位的位置。

128 应该是 8 (1000 0000) 64 应该是 7 (0100 0000)

【问题讨论】:

  • 把班次加起来就行了。
  • 为什么不__builtin_clz(在 GCC 上)或 BitScanReverse(在 MSVS 上)?
  • 128 编号为 7,而不是 8。
  • "128 应该是 8,64 应该是 7" (int)log2(x)+1
  • 您确定这些限制吗?如果可以用条件句,就写if (x &amp; (1 &lt;&lt; 7)) printf("7\n"); else if ...,好像太简单了。

标签: c binary bit-manipulation


【解决方案1】:

this question 启发,这个定义无环popcnt() 的解决方案应该可以解决您的问题:

#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>

static inline uint32_t popcnt(uint32_t x) {
    x -= ((x >> 1) & 0x55555555);
    x = (((x >> 2) & 0x33333333) + (x & 0x33333333));
    x = (((x >> 4) + x) & 0x0f0f0f0f);
    x += (x >> 8);
    x += (x >> 16);
    return x & 0x0000003f;
}

static inline uint32_t firstset(uint32_t x) {
    x |= (x >> 1);
    x |= (x >> 2);
    x |= (x >> 4);
    x |= (x >> 8);
    x |= (x >> 16);
    return popcnt(x);
}

int main() {
    uint32_t x;

    printf("Enter an integer: ");
    scanf("%"SCNu32, &x);

    printf("%"PRIu32"\n", firstset(x));

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-02
    • 2011-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    相关资源
    最近更新 更多