gpt4 book ai didi

c - 如何找到 C 中不同的第一位?

转载 作者:太空狗 更新时间:2023-10-29 17:06:39 26 4
gpt4 key购买 nike

我想与 C 中的整数进行比较,问题是找到不同的最低有效位。在 C 中执行此操作的最快方法是什么?

例子:

               Bit
3210
----
a = 13 (binary 1101)
b = 9 (binary 1001)
^

这里的结果应该是2,因为第2位是第一个不同的位。

最佳答案

ffs()来自 <strings.h>返回第一个位集的位置,其中位编号从 1 开始对于最低有效位(ffs(0) 返回零):

unsigned a = 0x0D;
unsigned b = 0x09;

unsigned x = a ^ b;
int pos = ffs(x) - 1;
if (pos == -1) {
// a and b are equal
} else {
// pos is the position of the first difference
}

关于c - 如何找到 C 中不同的第一位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21279844/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com