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

StringtoBin(byte n)
to Bin
String s = "";
for (int i = 7; i >= 0; i--)
    s += (n >> i) & 0x01;
return s;
StringtoBin(int bin, int size)
to Bin
String ret = Integer.toBinaryString(bin);
return normalizeNumber(ret, size);
StringtoBin(int size, String bitString)
to Bin
return String.format(String.format("%%%ds", size), bitString).replace(' ', '0');
StringBuffertoBin(int x)
to Bin
StringBuffer result = new StringBuffer();
result.append(x % 2);
x /= 2;
while (x > 0) {
    result.append(x % 2);
    x /= 2;
return result;
...
StringtoBin(long value, int width)
to Bin
char[] result = new char[width];
for (int cntr = 0; cntr < width; cntr++)
    result[width - cntr - 1] = (value & (0x1 << cntr)) == 0 ? '0' : '1';
return new String(result);
byte[]toBinArray(String hexStr)
to Bin Array
byte bArray[] = new byte[hexStr.length() / 2];
for (int i = 0; i < (hexStr.length() / 2); i++) {
    byte firstNibble = Byte.parseByte(hexStr.substring(2 * i, 2 * i + 1), 16); 
    byte secondNibble = Byte.parseByte(hexStr.substring(2 * i + 1, 2 * i + 2), 16);
    int finalByte = (secondNibble) | (firstNibble << 4); 
    bArray[i] = (byte) finalByte;
return bArray;
...
StringtoBinary(byte b)
to Binary
StringBuffer buf = new StringBuffer(8);
buf.append((b & (1 << 7)) == 0 ? '0' : '1');
buf.append((b & (1 << 6)) == 0 ? '0' : '1');
buf.append((b & (1 << 5)) == 0 ? '0' : '1');
buf.append((b & (1 << 4)) == 0 ? '0' : '1');
buf.append((b & (1 << 3)) == 0 ? '0' : '1');
buf.append((b & (1 << 2)) == 0 ? '0' : '1');
buf.append((b & (1 << 1)) == 0 ? '0' : '1');
...
StringtoBinary(byte b)
to Binary
return String.format("%8s", Integer.toBinaryString(b & 0xFF)).replace(' ', '0');
StringtoBinary(byte b)
Just for debugging and testing purposes
return String.format("%8s", Integer.toBinaryString(b & MOST_SIGNIFICANT_MASK)).replace(' ', '0');
StringtoBinary(byte b)
to Binary
return toBinary(b, BIN_PREFIX);