我有一个数字,我想把它打印成二进制。我不想通过写算法来实现。
Java中有没有内置函数?
我有一个数字,我想把它打印成二进制。我不想通过写算法来实现。
Java中有没有内置函数?
当前回答
解决方案使用32位显示掩码,
public static String toBinaryString(int n){
StringBuilder res=new StringBuilder();
//res= Integer.toBinaryString(n); or
int displayMask=1<<31;
for (int i=1;i<=32;i++){
res.append((n & displayMask)==0?'0':'1');
n=n<<1;
if (i%8==0) res.append(' ');
}
return res.toString();
}
System.out.println(BitUtil.toBinaryString(30));
O/P:
00000000 00000000 00000000 00011110
其他回答
看看这个逻辑可以把一个数字转换成任何进制
public static void toBase(int number, int base) {
String binary = "";
int temp = number/2+1;
for (int j = 0; j < temp ; j++) {
try {
binary += "" + number % base;
number /= base;
} catch (Exception e) {
}
}
for (int j = binary.length() - 1; j >= 0; j--) {
System.out.print(binary.charAt(j));
}
}
OR
StringBuilder binary = new StringBuilder();
int n=15;
while (n>0) {
if((n&1)==1){
binary.append(1);
}else
binary.append(0);
n>>=1;
}
System.out.println(binary.reverse());
我需要一些东西可以很好地打印出来,并把每n位的比特分开。换句话说,显示前导零并显示如下内容:
n = 5463
output = 0000 0000 0000 0000 0001 0101 0101 0111
我是这么写的:
/**
* Converts an integer to a 32-bit binary string
* @param number
* The number to convert
* @param groupSize
* The number of bits in a group
* @return
* The 32-bit long bit string
*/
public static String intToString(int number, int groupSize) {
StringBuilder result = new StringBuilder();
for(int i = 31; i >= 0 ; i--) {
int mask = 1 << i;
result.append((number & mask) != 0 ? "1" : "0");
if (i % groupSize == 0)
result.append(" ");
}
result.replace(result.length() - 1, result.length(), "");
return result.toString();
}
像这样调用它:
public static void main(String[] args) {
System.out.println(intToString(5463, 4));
}
试试这个方法:
public class Bin {
public static void main(String[] args) {
System.out.println(toBinary(0x94, 8));
}
public static String toBinary(int a, int bits) {
if (--bits > 0)
return toBinary(a>>1, bits)+((a&0x1)==0?"0":"1");
else
return (a&0x1)==0?"0":"1";
}
}
10010100
tostring (value,numbersystem)——使用的语法 然后传递值
Integer.toString(100,8) //打印144—八进制
Integer.toString(100,2) //打印1100100—二进制
Integer.toString(100,16) //打印64—十六进制
简单又简单的解决方法。
public static String intToBinaryString(int integer, int numberOfBits) {
if (numberOfBits > 0) { // To prevent FormatFlagsConversionMismatchException.
String nBits = String.format("%" + numberOfBits + "s", // Int to bits conversion
Integer.toBinaryString(integer))
.replaceAll(" ","0");
return nBits; // returning the Bits for the given int.
}
return null; // if the numberOfBits is not greater than 0, returning null.
}