Here you can find the source of countBits(long num)
Parameter | Description |
---|---|
num | number to count bits in it. |
public static byte countBits(long num)
//package com.java2s; //License from project: Open Source License public class Main { /**/* ww w . j a v a2 s . c om*/ * count 1 bits in nubmer. * <p> * {@literal 10: 1010 -> 2}<br> * {@literal 2: 10 -> 1}<br> * {@literal 56: 111000 -> 3}<br> * {@literal 34: 100010 -> 2}<br> * {@literal 255: 11111111 -> 8}<br> * {@literal 256: 100000000 -> 1}<br> * * @param num number to count bits in it. * * @return number of 1 bits. */ public static byte countBits(long num) { byte result; for (result = 0; Math.abs(num) > 0; result++) { num &= num - 1; } return result; } /** * count 1 bits in nubmer. * <p> * {@literal 10: 1010 -> 2}<br> * {@literal 2: 10 -> 1}<br> * {@literal 56: 111000 -> 3}<br> * {@literal 34: 100010 -> 2}<br> * {@literal 255: 11111111 -> 8}<br> * {@literal 256: 100000000 -> 1}<br> * * @param num number to count bits in it. * * @return number of 1 bits. */ public static byte countBits(int num) { byte result; for (result = 0; Math.abs(num) > 0; result++) { num &= num - 1; } return result; } /** * count 1 bits in nubmer. * <p> * {@literal 10: 1010 -> 2}<br> * {@literal 2: 10 -> 1}<br> * {@literal 56: 111000 -> 3}<br> * {@literal 34: 100010 -> 2}<br> * {@literal 255: 11111111 -> 8}<br> * {@literal 256: 100000000 -> 1}<br> * * @param num number to count bits in it. * * @return number of 1 bits. */ public static byte countBits(short num) { byte result; for (result = 0; num > 0; result++) { num &= num - 1; } return result; } /** * count 1 bits in nubmer. * <p> * {@literal 10: 1010 -> 2}<br> * {@literal 2: 10 -> 1}<br> * {@literal 56: 111000 -> 3}<br> * {@literal 34: 100010 -> 2}<br> * {@literal 255: 11111111 -> 8}<br> * {@literal 256: 100000000 -> 1}<br> * * @param num number to count bits in it. * * @return number of 1 bits. */ public static byte countBits(char num) { byte result; for (result = 0; num > 0; result++) { num &= num - 1; } return result; } /** * count 1 bits in nubmer. * <p> * {@literal 10: 1010 -> 2}<br> * {@literal 2: 10 -> 1}<br> * {@literal 56: 111000 -> 3}<br> * {@literal 34: 100010 -> 2}<br> * {@literal 255: 11111111 -> 8}<br> * {@literal 256: 100000000 -> 1}<br> * * @param num number to count bits in it. * * @return number of 1 bits. */ public static byte countBits(byte num) { byte result; for (result = 0; num > 0; result++) { num &= num - 1; } return result; } }