位为专题

一个正整数int有多少bit位为一

https://leetcode.com/problems/number-of-1-bits/ 题目 给一个正整数int,输出bit位为一的个数。 解法1 public static int bitCount(int x) {int count = 0;while(x > 0) {count += (x % 2);x = x / 2;}return count;}如果是9 计算4

编写一个函数getbits,从一个十六位的单元中取出某几位(即该几位保留原值,其余位为0)。函数调用形式为:getbits(value1,n1,n2)

原理如下: 对一个8进制数101675 二进制为 1 0 0 0 0 0 1 1 1 0 1 1 1 1 0 1 取出5~8位(从右往左取) 此时先将101675<<(右移)5位 左边补0 此时变为 0 0 0 0 0 1 0 0 0 0 0 1 1 1 0 1 想要取出5~8位 此时只需要& 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 想要得到这样一个0 0 0 0 0 0