Question

J'ai besoin d'imprimer une variable de type byte dans un format non signé. Comment puis-je faire?

Était-ce utile?

La solution

Voulez-vous dire que vous commencez avec un int signé et que vous voulez la valeur absolue? Vous pouvez faire quelque chose comme ceci:

    byte b = Byte.parseByte("-9");
    int i = (int) b;

    System.out.println(Math.abs(i));

Autres conseils

Je viens d'écrire cette méthode pour vous.

public static String printUnsignedByte(byte b){
    StringBuilder sb = new StringBuilder();
    while(b>0){
        sb.insert(0, b%2==0?0:1);
        b>>=1;
    }
    for(int i = 8-sb.length(); i>0; i--){
        sb.insert(0,0);
    }
    return sb.toString();
}

EDIT: Mais il ne couvre pas le format de complément à 2. Avez-vous besoin aussi? EDIT2: Départ:

Integer.toBinaryString(2)

il couvre 2es compliment pour les valeurs négatives, mais la sortie est trop long, il pribts 4 bits. Il suffit de raccourcir ce avec vous et substring fait.

Edit 3:. Ma solution finale

public static String printUnsignedByte(byte b){
    if(b>0){
        StringBuilder ret = new StringBuilder(Integer.toBinaryString(b));
        for(int i = 8-ret.length(); i>0; i--){
            ret.insert(0,0);
        }
        return ret.toString();
    }else{
        return Integer.toBinaryString(b).substring(24);
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top