Tuesday, March 24, 2015

Convert a string to binary int

Convert a string to binary int.
For example, string "foo", after convert "foo", the output should be 01100110 01101111 01101111.

Solution:

public static void convert(String str) {
    byte[] bytes = str.getBytes();
    StringBuilder binary = new StringBuilder();
    for(byte b : bytes) {
        int val = b;
        for(int i = 0; i < 8; i++) {
            if((val & 128) == 0) {
                binary.append(0);
            }else {
                binary.append(1);
            }
            val = (val << 1);
        }
        binary.append(" ");
    }
  
    System.out.println("'" + str + "' to binary: " + binary);
 }

No comments:

Post a Comment