Conversion d'un int à une représentation de chaîne binaire en Java?
Question
Quelle serait la meilleure façon (idéalement, plus simple) pour convertir un entier à une représentation de chaîne binaire en Java?
Par exemple, supposons que l'int est 156. La représentation de chaîne binaire de ce serait « 10011100 ».
La solution
Integer.toBinaryString(int i)
Autres conseils
Il y a aussi la
public static string intToBinary(int n)
{
string s = "";
while (n > 0)
{
s = ( (n % 2 ) == 0 ? "0" : "1") +s;
n = n / 2;
}
return s;
}
Un plus Way- En utilisant java.lang.Integer vous pouvez obtenir une représentation de chaîne de la première i
argument dans le radix (Octal - 8, Hex - 16, Binary - 2)
spécifié par le second argument.
Integer.toString(i, radix)
Exemple _
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
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));
}
}
Ceci est quelque chose que j'ai écrit il y a quelques minutes juste déconner. 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();
}
}
En utilisant la fonction intégrée:
String binaryNum = Integer.toBinaryString(int num);
Si vous ne souhaitez pas utiliser la fonction intégrée pour convertir en binaire int alors vous pouvez aussi faire ceci:
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());
}
}
Convertir entier en binaire:
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)));
}
}
Sortie:
Entrée Entier:
10
Nombre binaire: 1010
La plus simple approche est de vérifier si le nombre est ou non impair. Si elle est, par définition, le numéro le plus à droite binaire sera « 1 » (2 ^ 0). Après que nous avons déterminé, nous décaler le nombre mordit à droite et à vérifier la même valeur en utilisant récursion.
@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());
}
}
Voici mes méthodes, il est un peu convaincu que le nombre d'octets fixes
private void printByte(int value) {
String currentBinary = Integer.toBinaryString(256 + value);
System.out.println(currentBinary.substring(currentBinary.length() - 8));
}
public int binaryToInteger(String binary) {
char[] numbers = binary.toCharArray();
int result = 0;
for(int i=numbers.length - 1; i>=0; i--)
if(numbers[i]=='1')
result += Math.pow(2, (numbers.length-i - 1));
return result;
}
Utilisation décalage de bits est un peu plus vite ...
public static String convertDecimalToBinary(int N) {
StringBuilder binary = new StringBuilder(32);
while (N > 0 ) {
binary.append( N % 2 );
N >>= 1;
}
return binary.reverse().toString();
}
Cela peut être exprimé en tant que pseudo-code:
while(n > 0):
remainder = n%2;
n = n/2;
Insert remainder to front of a list or push onto a stack
Print list or stack
Vous devriez vraiment utiliser Integer.toBinaryString () (comme indiqué ci-dessus), mais si pour une raison quelconque, vous voulez votre propre:
// Like Integer.toBinaryString, but always returns 32 chars
public static String asBitString(int value) {
final char[] buf = new char[32];
for (int i = 31; i >= 0; i--) {
buf[31 - i] = ((1 << i) & value) == 0 ? '0' : '1';
}
return new String(buf);
}
public class BinaryConverter {
public static String binaryConverter(int number) {
String binary = "";
if (number == 1){
binary = "1";
System.out.print(binary);
return binary;
}
if (number == 0){
binary = "0";
System.out.print(binary);
return binary;
}
if (number > 1) {
String i = Integer.toString(number % 2);
binary = binary + i;
binaryConverter(number/2);
}
System.out.print(binary);
return binary;
}
}
Cela devrait être assez simple avec quelque chose comme ceci:
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();
}
Vous pouvez utiliser en boucle et pour convertir un entier en binaire. Comme cela,
import java.util.Scanner;
public class IntegerToBinary
{
public static void main(String[] args)
{
int num;
String str = "";
Scanner sc = new Scanner(System.in);
System.out.print("Please enter the a number : ");
num = sc.nextInt();
while(num > 0)
{
int y = num % 2;
str = y + str;
num = num / 2;
}
System.out.println("The binary conversion is : " + str);
sc.close();
}
}
Source et référence - convertir int en binaire en java exemple.