如何获得C中最右置位的位置 [英] How to get position of right most set bit in C

查看:78
本文介绍了如何获得C中最右置位的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int a = 12;

例如:二进制数为12的是1100,因此当设置了从右数第3位时,答案应该为3.

for eg: binary of 12 is 1100 so answer should be 3 as 3rd bit from right is set.

我想要 a 的最后设置位的位置.谁能告诉我该怎么做.

I want the position of the last most set bit of a. Can anyone tell me how can I do so.

注意:我只想要位置,在这里我不想设置或重置该位.因此,它不是关于stackoverflow的任何问题的重复.

NOTE : I want position only, here I don't want to set or reset the bit. So it is not duplicate of any question on stackoverflow.

推荐答案

尝试一下

int set_bit = n ^ (n&(n-1));

这篇关于如何获得C中最右置位的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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