在 Java 中将 int 转换为二进制字符串表示?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2406432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting an int to a binary string representation in Java?
提问by Tyler Treat
What would be the best way (ideally, simplest) to convert an int to a binary string representation in Java?
在 Java 中将 int 转换为二进制字符串表示的最佳方法(理想情况下,最简单)是什么?
For example, say the int is 156. The binary string representation of this would be "10011100".
例如,假设 int 是 156。它的二进制字符串表示将是“10011100”。
采纳答案by Hyman
Integer.toBinaryString(int i)
回答by izilotti
There is also the java.lang.Integer.toString(int i, int base)method, which would be more appropriate if your code might one day handle bases other than 2 (binary).
还有java.lang.Integer.toString(int i, int base)方法,如果您的代码有一天可能会处理 2(二进制)以外的基数,则该方法会更合适。
回答by Rupesh Yadav
One more way- By using java.lang.Integeryou can get string representation of the first argument i
in the radix (Octal - 8, Hex - 16, Binary - 2)
specified by the second argument.
还有一个way-通过使用java.lang.Integer中,你可以得到的第一个参数的字符串表示i
在radix (Octal - 8, Hex - 16, Binary - 2)
通过第二个参数指定。
Integer.toString(i, radix)
Example_
例子_
private void getStrtingRadix() {
// TODO Auto-generated method stub
/* returns the string representation of the
unsigned integer in concern radix*/
System.out.println("Binary eqivalent of 100 = " + Integer.toString(100, 2));
System.out.println("Octal eqivalent of 100 = " + Integer.toString(100, 8));
System.out.println("Decimal eqivalent of 100 = " + Integer.toString(100, 10));
System.out.println("Hexadecimal eqivalent of 100 = " + Integer.toString(100, 16));
}
OutPut_
输出_
Binary eqivalent of 100 = 1100100
Octal eqivalent of 100 = 144
Decimal eqivalent of 100 = 100
Hexadecimal eqivalent of 100 = 64
回答by Artavazd Manukyan
public class Main {
public static String toBinary(int n, int l ) throws Exception {
double pow = Math.pow(2, l);
StringBuilder binary = new StringBuilder();
if ( pow < n ) {
throw new Exception("The length must be big from number ");
}
int shift = l- 1;
for (; shift >= 0 ; shift--) {
int bit = (n >> shift) & 1;
if (bit == 1) {
binary.append("1");
} else {
binary.append("0");
}
}
return binary.toString();
}
public static void main(String[] args) throws Exception {
System.out.println(" binary = " + toBinary(7, 4));
System.out.println(" binary = " + Integer.toString(7,2));
}
}
回答by AbbyPaden
This is something I wrote a few minutes ago just messing around. Hope it helps!
这是我几分钟前写的东西,只是乱七八糟。希望能帮助到你!
public class Main {
public static void main(String[] args) {
ArrayList<Integer> powers = new ArrayList<Integer>();
ArrayList<Integer> binaryStore = new ArrayList<Integer>();
powers.add(128);
powers.add(64);
powers.add(32);
powers.add(16);
powers.add(8);
powers.add(4);
powers.add(2);
powers.add(1);
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to Paden9000 binary converter. Please enter an integer you wish to convert: ");
int input = sc.nextInt();
int printableInput = input;
for (int i : powers) {
if (input < i) {
binaryStore.add(0);
} else {
input = input - i;
binaryStore.add(1);
}
}
String newString= binaryStore.toString();
String finalOutput = newString.replace("[", "")
.replace(" ", "")
.replace("]", "")
.replace(",", "");
System.out.println("Integer value: " + printableInput + "\nBinary value: " + finalOutput);
sc.close();
}
}
}
回答by Rachit Srivastava
Using built-in function:
使用内置函数:
String binaryNum = Integer.toBinaryString(int num);
If you don't want to use the built-in function for converting int to binary then you can also do this:
如果您不想使用内置函数将 int 转换为二进制,那么您也可以这样做:
import java.util.*;
public class IntToBinary {
public static void main(String[] args) {
Scanner d = new Scanner(System.in);
int n;
n = d.nextInt();
StringBuilder sb = new StringBuilder();
while(n > 0){
int r = n%2;
sb.append(r);
n = n/2;
}
System.out.println(sb.reverse());
}
}
回答by Sidarth
Convert Integer to Binary:
将整数转换为二进制:
import java.util.Scanner;
public class IntegerToBinary {
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
System.out.println("Enter Integer: ");
String integerString =input.nextLine();
System.out.println("Binary Number: "+Integer.toBinaryString(Integer.parseInt(integerString)));
}
}
Output:
输出:
Enter Integer:
输入整数:
10
10
Binary Number: 1010
二进制数:1010
回答by wild_nothing
The simplest approach is to check whether or not the number is odd. If it is, by definition, its right-most binary number will be "1" (2^0). After we've determined this, we bit shift the number to the right and check the same value using recursion.
最简单的方法是检查数字是否为奇数。如果是,根据定义,它最右边的二进制数将为“1”(2^0)。在我们确定这一点后,我们将数字右移并使用递归检查相同的值。
@Test
public void shouldPrintBinary() {
StringBuilder sb = new StringBuilder();
convert(1234, sb);
}
private void convert(int n, StringBuilder sb) {
if (n > 0) {
sb.append(n % 2);
convert(n >> 1, sb);
} else {
System.out.println(sb.reverse().toString());
}
}
回答by Ariel Badilla
public static string intToBinary(int n)
{
string s = "";
while (n > 0)
{
s = ( (n % 2 ) == 0 ? "0" : "1") +s;
n = n / 2;
}
return s;
}
回答by Sandeep Saini
This should be quite simple with something like this :
这应该很简单,如下所示:
public static String toBinary(int number){
StringBuilder sb = new StringBuilder();
if(number == 0)
return "0";
while(number>=1){
sb.append(number%2);
number = number / 2;
}
return sb.reverse().toString();
}