Java Utililty Methods Binary Encode

List of utility methods to do Binary Encode

Description

The list of methods to do Binary Encode are organized into topic(s).

Method

StringtoBinaryString(byte[] bytes)
Converts byte array to a binary String by MSB order.
return toBinaryString(bytes, true);
StringtoBinaryString(byte[] bytes, int bitSize)
to Binary String
StringBuilder stringBuilder = new StringBuilder(bitSize);
for (int i = 0, byteSize = (int) Math.ceil(bitSize / 8.0); i < byteSize; i++) {
    for (int j = 0; j < 8 && i * 8 + j < bitSize; j++) {
        stringBuilder.append(bytes[i] >> (7 - j) & 0x1);
return stringBuilder.toString();
StringtoBinaryString(byte[] data, boolean format)
to Binary String
return toBinaryString(data, 0, -1, 0, format);
StringtoBinaryString(char value)
to Binary String
byte[] b = new byte[16];
int cnt = 0;
for (int i = 15; i > -1; i--) {
    b[cnt++] = (value & mask[i]) == 0 ? b0 : b1;
return new String(b);
StringtoBinaryString(final boolean[] bits)
Converts an array of boolean into a string using the toDigit method.
final StringBuilder builder = new StringBuilder(bits.length);
for (final boolean bit : bits) {
    builder.append(toDigit(bit));
return builder.toString();
StringtoBinaryString(final byte number)
to Binary String
final StringBuilder builder = new StringBuilder(Byte.SIZE);
for (int i = 0; i < Byte.SIZE; i++) {
    final int q = number & POWERS[Byte.SIZE - 1 - i];
    builder.append(q != 0 ? '1' : '0');
return builder.toString();
StringtoBinaryString(final char[] arr)
to Binary String
final StringBuilder buffer = new StringBuilder();
buffer.append('[');
if (arr.length > 0)
    buffer.append(Integer.toBinaryString(arr[0]));
for (int i = 1; i < arr.length; i++) {
    buffer.append(' ');
    buffer.append(Integer.toBinaryString(arr[i]));
buffer.append(']');
return buffer.toString();
StringtoBinaryString(int a, int bits)
to Binary String
return String.format("%" + bits + "s", Integer.toBinaryString(a)).replace(' ', '0');
StringtoBinaryString(int b, int bits)
to Binary String
int v = 1 << (bits - 1);
String s = "";
for (int i = 0; i < bits; i++) {
    if ((b & v) == v) {
        s += "1";
    } else {
        s += "0";
    v >>= 1;
return s;
StringtoBinaryString(int l, int L)
ToBinaryString - use to go through all 'L' binary combinations.
String sb = new String(Integer.toBinaryString(l));
while (sb.length() < L) {
    sb = "0" + sb;
return sb;