如何在int中找到最低有效位(LSB)的位置? c ++

问题描述 投票:0回答:1

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

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

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

c++ int position bit
1个回答
0
投票
您不需要知道LSB的位置。这非常好,因为由于endianness,它可能在多个位置!

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

检查一下

您没有要求这个,但是我也可以添加它。要检查一点,请将数字n右移,然后按位与之相交:

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

将第n位更改为x

将第n位设置为1或0可以通过对2的补码C ++实现进行以下操作:

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 nth bit to lsb_value */ return x; }

© www.soinside.com 2019 - 2024. All rights reserved.