【问题标题】:How to find a position of Least Significant Bit (LSB) in an int? c++如何在 int 中找到最低有效位 (LSB) 的位置? C++
【发布时间】:2020-01-16 15:33:27
【问题描述】:

我必须编写一个 c++ 函数来交换 int 的第 n 位和最低有效位。我找到了一些例子并这样做了:

v1 = v1 ^ ((((v1&1) ^ (v1>>n)&1) << LSBpos) | (((v1&1) ^ (v1>>n)&1) << n));
cout<<v1;

v1 是一个整数。 v1&1 是 LSB 的值。 LSBpos 应该是 LSB 的位置,但是我不知道怎么弄。有关于如何获得设置或清除的 LSB 位置的说明,但我只需要该位置,无论是否设置。

【问题讨论】:

  • 最低有效位是 C++ 中的第 0 位。你的意思是最少设置位吗?

标签: c++ int position bit


【解决方案1】:

您不需要知道 LSB 的位置。这很棒,因为 endianness 它可能在多个地方!

让我们寻求帮助:How do you set, clear, and toggle a single bit?:

检查一下

你没有要求这个,但我不妨添加它。 要检查一下,请将数字 n 向右移动,然后按位与它:

bit = (number >> n) & 1U;

将第 n 位更改为 x

在 2 的补码 C++ 实现中,将第 n 位设置为 1 或 0 可以通过以下方式实现:

number ^= (-x ^ number) & (1UL << n);

去吧!

int swap_nth_and_lsb(int x, int n)
{
    // let to the reader: check the validity of n

    // read LSB and nth bit
    int const lsb_value = x& 1U;
    int const nth_value = (x>> n) & 1U;

    // swap
    x ^= (-lsb_value) & (1UL << n);
    x ^= /* let to the reader: set the lsb to nth_value */

    return x;
}

在评论中,OP 说“我必须写一行代码才能得到结果”。好吧,如果单行条件成立,你可以从上面的解决方案开始,一步一步变成单行。

【讨论】:

    猜你喜欢
    • 2013-11-13
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 2010-10-19
    • 1970-01-01
    • 2020-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多