Java Long.bitCount()
方法
原文:https://www.studytonight.com/java-wrapper-class/java-long-bitcount-method
Java bitCount()
方法属于Long
类。此方法用于返回指定长值的二进制补码形式的一位总数。
语法:
public static int bitCount(long i)
参数:
传递的唯一参数是长 I,它将返回二进制补码形式的一位的总数。
返回:
该方法返回长值的二进制补码形式的一位总数,因此其返回类型为int.
例 1:
在这里,我们输入一个长数字 365。Long.toBinaryString()
方法会将数字转换为其等价的二进制字符串( 101101101 为整数 365 )。那么将返回二进制表示中一位的总数。
import java.lang.Long;
public class StudyTonight
{
public static void main(String[] args)
{
long i = 365;
long j = -365;
System.out.println("Actual Number is " + i);
// converting the number to its equivalent binary form with base 2
System.out.println("Binary conversion of" + i + " = " + Long.toBinaryString(i));
//returning the number of one-bits
System.out.println("Number of one bits = " + Long.bitCount(i));
System.out.println("*******************");
System.out.println("Actual Number is " + j);
System.out.println("Binary conversion of" + j + " = " + Long.toBinaryString(j));
System.out.println("Number of one bits = " + Long.bitCount(j));
}
}
实际数为 365 二进制转换的 365 = 101101101 一位数= 6
- T4】实际数为-365 二进制转换的-365 = 11111111111111111111111111111111111111111111111111111111111111111111111111110101010101010111111111111111111
例 2:
这里,我们取一个长值数组。Long.toBinaryString()
方法将数组中的数字转换成二进制字符串。
import java.lang.Long;
public class StudyTonight
{
public static void main(String args[])
{
long [] set = {72, 78, 56, 89,80, 66};
try
{
for(int i=0; i<6; i++)
{
//Converting the actual number to binary String
String b = Long.toBinaryString(set[i]);
//Converting the binary String to binary long of base 2
long c = Long.parseLong(b,2);
//Counting the set bits
int d = Long.bitCount(c);
System.out.println("Actual number is "+ set[i] +" binary sequence : " + b + ",number of set bits are : " + d);
}
}
catch(Exception e)
{
System.out.println("Exception caught: " + e);
}
}
}
实际数为 72 二进制序列:1001000,设置位数为:2 实际数为 78 二进制序列:1001110,设置位数为:4 实际数为 56 二进制序列:111000,设置位数为:3 实际数为 89 二进制序列:1011001,设置位数为:4 实际数为 80 二进制序列:1010000,设置位数
例 3:
这里有一个通用的例子,用户可以输入他选择的数字并获得所需的输出。try
和catch
块( Java Try and Catch )用于处理程序执行过程中发生的任何异常。(例如,用户输入字符串等。代替长值)。
import java.lang.Long;
import java.util.*;
public class StudyTonight
{
public static void main(String[] args)
{
System.out.println("Enter number");
Scanner sc = new Scanner(System.in);
try
{
long i = sc.nextLong();
System.out.println("Actual Number is " + i);
// converting the number to its equivalent binary form with base 2
System.out.println("Binary conversion of " +i+ " = " + Long.toBinaryString(i));
//returning the number of one-bits
System.out.println("Number of one bits = " + Long.bitCount(i));
}
catch( Exception e)
{
System.out.println("Error!!");
}
}
}
输入编号 895687 实际编号为 895687 二进制转换为 895687 = 110110101011000111 一位数= 12
- *输入编号 -533 实际编号为-533 二进制转换为!
实时示例:
在这里,您可以测试实时代码示例。您可以为不同的值执行示例,甚至可以编辑和编写您的示例来测试 Java 代码。