JavaWritten in English

Displaying binary value of byte

During my fights with 7z format I realized a need to see a value of byte in binary representation. Unfortunatelly there is no good way in Java, how to display binary value for the byte primitive. The method Integer.toBinaryString() takes int as its argument and a conversion byte to int does not work well for negative numbers. Following code will print a range of byte values:

public class Test {
    public static void main(String[] args) {

        byte b = -127;
        for (int i = 0; i < 255; i++) {
            System.out.println(String.format("%4d = 0x%02X = ", b, b) + printBinary(b));
            b++;
        }
    }

    public static String printBinary(byte number) {
        StringBuilder sb = new StringBuilder(8);
        for (int i = 8; i-- > 0;) {
            sb.append(((number & (1 << i)) != 0) ? 1 : 0);
        }
        return sb.toString();
    }
}

Napsat komentář

Vaše e-mailová adresa nebude zveřejněna. Vyžadované informace jsou označeny *

Tato stránka používá Akismet k omezení spamu. Podívejte se, jak vaše data z komentářů zpracováváme..