Last active
May 25, 2018 02:24
-
-
Save jeffrade/81556ddbb53f88bb2b7555ec12cc6b3e to your computer and use it in GitHub Desktop.
Covert a String object to String binary representation in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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