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

StringtoBinary(byte[] bytes)
to Binary
StringBuilder sb = new StringBuilder(bytes.length * Byte.SIZE);
for (int i = 0; i < Byte.SIZE * bytes.length; i++) {
    sb.append((bytes[i / Byte.SIZE] << i % Byte.SIZE & 0x80) == 0 ? '0' : '1');
return sb.toString();
byte[]toBinary(final byte[] array, final int offset, final int length)
to Binary
final byte[] result = new byte[length];
for (int i = offset, j = 0; j < length; i++, j++) {
    result[j] = array[i];
return result;
StringtoBinary(final byte[] bytes)
Turn a byte array into 1's and 0's (in a String)
final StringBuilder sb = new StringBuilder(bytes.length * Byte.SIZE);
for (int i = 0; i < Byte.SIZE * bytes.length; i++) {
    sb.append((bytes[i / Byte.SIZE] << i % Byte.SIZE & 0x80) == 0 ? '0' : '1');
return sb.toString();
doubletoBinary(final double d)
Convert bipolar to binary.
return (d + 1) / 2.0;
doubletoBinary(final double d)
to Binary
return (d + 1) / 2.0;
byte[]toBinary(final Object o)
to Binary
if (o instanceof byte[]) {
    return (byte[]) o;
} else if (o == null) {
    return null;
} else if (o instanceof String) {
    return ((String) o).getBytes();
} else {
    throw new IllegalArgumentException("Can't parse as binary:" + o);
...
StringtoBinary(int nr, int bits)
to Binary
String binval = "";
int val;
int i = bits;
do {
    val = power(2, i);
    if (nr > val) {
        binval = binval + "1";
        nr = nr - val;
...
boolean[]toBinary(int number, int length)
Convert number to binary array representation.
final boolean[] binary = new boolean[length];
for (int i = 0; i < length; i++) {
    binary[length - 1 - i] = (1 << i & number) != 0;
return binary;
StringtoBinary(int val)
to Binary
StringBuilder builder = new StringBuilder();
builder.append("0x").append(Integer.toHexString(val)).append(" = ");
for (int i = 31; i >= 0; i--) {
    String digit = ((1 << i) & val) == 0 ? "0" : "1";
    builder.append(digit).append((i % 4 == 0) ? " " : "");
return builder.toString();
StringtoBinary(int value, int bits)
Converts an integer to a binary string
StringBuffer sb = new StringBuffer();
int mask = 1 << (bits - 1);
for (int i = 0; i < bits; i++) {
    if ((value & mask) == 0) {
        sb.append('0');
    } else {
        sb.append('1');
    mask >>= 1;
return sb.toString();