Comment obtenir une représentation binaire 0-padded d'un entier en java?

par exemple, pour 1, 2, 128, 256 la sortie peut être (16 chiffres):

0000000000000001
0000000000000010
0000000010000000
0000000100000000

j'ai essayé

String.format("%16s", Integer.toBinaryString(1));

il met des espaces pour le rembourrage gauche:

`               1'

comment mettre 0 s pour le rembourrage. Je ne l'ai pas trouvé dans Formatter . Est-il une autre façon de le faire?

Merci d'avance.

P. S. ce post décrit comment formater des entiers avec le 0-padding gauche, mais il n'est pas pour la représentation binaire.

92
demandé sur Community 2010-12-12 14:30:59

15 réponses

je pense que c'est une solution sous-optimale, mais vous pourriez le faire

String.format("%16s", Integer.toBinaryString(1)).replace(' ', '0')
160
répondu Samuel Parsonage 2010-12-12 11:41:59

il n'y a pas de conversion binaire intégrée dans le java.util.Formateur, je vous conseille d'utiliser de la Chaîne.remplacer le caractère d'espace par des zéros, comme suit:

String.format("%16s", Integer.toBinaryString(1)).replace(" ", "0")

ou mettre en œuvre votre propre logique pour convertir des entiers à la représentation binaire avec le rembourrage gauche ajouté quelque part le long des lignes données dans ce ainsi. Ou si vous avez vraiment besoin de passer des nombres au format, vous pouvez convertir votre représentation binaire en BigInteger et puis formater cela avec des zéros de tête, mais cela est très coûteux à l'exécution, comme dans:

String.format("%016d", new BigInteger(Integer.toBinaryString(1)))
18
répondu Zoran Regvart 2017-05-23 12:03:02

j'ai essayé toutes sortes d'appels de méthode que je n'ai pas vraiment utilisé avant pour faire ce travail, ils ont travaillé avec un succès modéré, jusqu'à ce que je pense à quelque chose qui est si simple que ça pourrait fonctionner, et il a fait!

je suis sûr qu'il a été pensé avant, pas sûr si c'est bon pour la longue chaîne de codes binaires, mais il fonctionne très bien pour les chaînes de 16Bit. Espérons que cela aide!! (Note: la deuxième partie du code est améliorée)

String binString = Integer.toBinaryString(256);
  while (binString.length() < 16) {    //pad with 16 0's
        binString = "0" + binString;
  }

grâce à Will aider à améliorer cette réponse pour le faire fonctionner avec une boucle. Cela peut-être un peu maladroit, mais il fonctionne, s'il vous plaît améliorer et commenter retour si vous le pouvez....

binString = Integer.toBinaryString(256);
int length = 16 - binString.length();
char[] padArray = new char[length];
Arrays.fill(padArray, '0');
String padString = new String(padArray);
binString = padString + binString;
8
répondu Tom Spencer 2012-10-12 12:04:32

vous pouvez utiliser Apache Commons StringUtils . Il propose des méthodes pour capitonner les cordes:

StringUtils.leftPad(Integer.toBinaryString(1), 16, '0');
8
répondu Michal B 2013-05-08 08:04:54

Voici une nouvelle réponse pour un ancien poste.

pour pad une valeur binaire avec des zéros menant à une longueur spécifique, essayez ceci:

Integer.toBinaryString( (1 << len) | val ).substring( 1 )

si len = 4 et val = 1 ,

Integer.toBinaryString( (1 << len) | val )

renvoie la chaîne "10001" , puis

"10001".substring( 1 )

écarte le tout premier personnage. Nous obtenons donc ce que nous voulons:

"0001"

Si val est susceptible d'être négatif, plutôt essayer:

Integer.toBinaryString( (1 << len) | (val & ((1 << len) - 1)) ).substring( 1 )
5
répondu Cr4paud 2015-01-28 17:40:14

essayez...

String.format("%016d\n", Integer.parseInt(Integer.toBinaryString(256)));

je ne pense pas que c'est la "bonne" façon de le faire... mais il fonctionne :)

3
répondu Paul 2010-12-12 11:45:03

Je ne sais pas" bonne " solution, mais je peux vous suggérer un patch rapide.

String.format("%16s", Integer.toBinaryString(1)).replace(" ", "0");

je viens de l'essayer et j'ai vu qu'il fonctionne très bien.

3
répondu AlexR 2010-12-12 11:58:12

une version plus simple de l'idée de user3608934 "C'est un vieux truc, créer une chaîne de caractères avec 16 0 puis Ajouter la chaîne de caractères binaires tronqués que vous avez":

private String toBinaryString32(int i) {
    String binaryWithOutLeading0 = Integer.toBinaryString(i);
    return "00000000000000000000000000000000"
            .substring(binaryWithOutLeading0.length())
            + binaryWithOutLeading0;
}
2
répondu bento 2014-06-19 11:15:56

une solution naïve que le travail serait

String temp = Integer.toBinaryString(5);
while (temp.length() < Integer.SIZE) temp = "0"+temp; //pad leading zeros
temp = temp.substring(Integer.SIZE - Short.SIZE); //remove excess

une autre méthode serait

String temp = Integer.toBinaryString((m | 0x80000000));
temp = temp.substring(Integer.SIZE - Short.SIZE);

cela produira une chaîne de 16 bits de l'entier 5

1
répondu proeng 2015-03-17 16:02:11

c'est un vieux truc, créer une chaîne avec 16 0 puis Ajouter la chaîne binaire tronquée que vous avez obtenu à partir de la chaîne.format ("%s", entier.toBinaryString (1)) et utilisez les 16 caractères les plus à droite, en détachant n'importe quel 0. Mieux encore, faites une fonction qui vous permet de spécifier combien de temps d'une chaîne binaire vous voulez. Bien sûr, il y a probablement un bazillion d'autres façons d'accomplir ceci, y compris les bibliothèques, mais j'Ajoute ce post pour aider un ami :)

public class BinaryPrinter {

    public static void main(String[] args) {
        System.out.format("%d in binary is %s\n", 1, binaryString(1, 4));
        System.out.format("%d in binary is %s\n", 128, binaryString(128, 8));
        System.out.format("%d in binary is %s\n", 256, binaryString(256, 16));
    }

    public static String binaryString( final int number, final int binaryDigits ) {
        final String pattern = String.format( "%%0%dd", binaryDigits );
        final String padding = String.format( pattern, 0 );
        final String response = String.format( "%s%s", padding, Integer.toBinaryString(number) );

        System.out.format( "\npattern = '%s'\npadding = '%s'\nresponse = '%s'\n\n", pattern, padding, response );

        return response.substring( response.length() - binaryDigits );
    }
}
0
répondu user3608934 2014-05-06 15:41:12

j'écrirais ma propre classe util avec la méthode comme ci-dessous

public class NumberFormatUtils {

public static String longToBinString(long val) {
    char[] buffer = new char[64];
    Arrays.fill(buffer, '0');
    for (int i = 0; i < 64; ++i) {
        long mask = 1L << i;
        if ((val & mask) == mask) {
            buffer[63 - i] = '1';
        }
    }
    return new String(buffer);
}

public static void main(String... args) {
    long value = 0b0000000000000000000000000000000000000000000000000000000000000101L;
    System.out.println(value);
    System.out.println(Long.toBinaryString(value));
    System.out.println(NumberFormatUtils.longToBinString(value));
}

}

sortie:

5
101
0000000000000000000000000000000000000000000000000000000000000101

La même approche pourrait être appliquée à tous les types intégraux. Faites attention au type de masque

long mask = 1L << i;

0
répondu Arseny Kovalchuk 2015-02-17 19:05:15

cette méthode convertit un int en chaîne, longueur=bits. Soit avec un zéro, soit avec les bits les plus significatifs tronqués.

static String toBitString( int x, int bits ){
    String bitString = Integer.toBinaryString(x);
    int size = bitString.length();
    StringBuilder sb = new StringBuilder( bits );
    if( bits > size ){
        for( int i=0; i<bits-size; i++ )
            sb.append('0');
        sb.append( bitString );
    }else
        sb = sb.append( bitString.substring(size-bits, size) );

    return sb.toString();
}
0
répondu jenfax 2015-02-24 00:40:20

vous pouvez utiliser lib https://github.com/kssource/BitSequence . Il accepte un nombre et renvoie une chaîne bynaire, capitonnée et / ou groupée.

String s = new BitSequence(2, 16).toBynaryString(ALIGN.RIGHT, GROUP.CONTINOUSLY));  
return  
0000000000000010  

another examples:

[10, -20, 30]->00001010 11101100 00011110
i=-10->00000000000000000000000000001010
bi=10->1010
sh=10->00 0000 0000 1010
l=10->00000001 010
by=-10->1010
i=-10->bc->11111111 11111111 11111111 11110110
0
répondu Nikmass 2015-11-15 14:36:36
for(int i=0;i<n;i++)
{
  for(int j=str[i].length();j<4;j++)
  str[i]="0".concat(str[i]);
}

str[i].length() est la longueur du nombre disons 2 en binaire est 01 Qui est la longueur 2 changer 4 à la longueur maximale désirée du nombre. Ceci peut être optimisé en O (n). en utilisant continue.

0
répondu Jasmeet Chhabra 2017-08-05 20:54:58

// ci-Dessous permettra de gérer correctement les tailles

public static String binaryString(int i) {
    return String.format("%" + Integer.SIZE + "s", Integer.toBinaryString(i)).replace(' ', '0');
}

public static String binaryString(long i) {
    return String.format("%" + Long.SIZE + "s", Long.toBinaryString(i)).replace(' ', '0');
}
0
répondu Paul Weiss 2018-03-29 14:10:59