Skip to content

Instantly share code, notes, and snippets.

@jeffrade
Last active May 25, 2018 02:24
Show Gist options
  • Save jeffrade/81556ddbb53f88bb2b7555ec12cc6b3e to your computer and use it in GitHub Desktop.
Save jeffrade/81556ddbb53f88bb2b7555ec12cc6b3e to your computer and use it in GitHub Desktop.
Covert a String object to String binary representation in Java
public class StringToBinary {
// https://stackoverflow.com/a/917190
public static void main(String[] args) {
final String s = args.length > 0 ? args[0] : "foo";
final byte[] bytes = s.getBytes();
StringBuilder binary = new StringBuilder();
for (byte b : bytes) {
int val = b;
System.out.println("byte b=" + b);
System.out.println("int val=" + val);
for (int i = 0; i < 8; i++) {
final int bit = (val & 128) == 0 ? 0 : 1;
System.out.println("int bit=" + bit);
binary.append(bit);
val <<= 1;// https://stackoverflow.com/a/141873
System.out.println("shf val=" + val);
}
binary.append(' ');
System.out.println("==============================");
}
System.out.println(s);
System.out.println(binary);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment