change string into binary uding java

Solutions on MaxInterview for change string into binary uding java by the best coders in the world

showing results for - "change string into binary uding java"
Mekhi
22 Apr 2020
1
2package com.mkyong.crypto.bytes;
3
4import java.util.ArrayList;
5import java.util.List;
6import java.util.stream.Collectors;
7
8public class StringToBinaryExample1 {
9
10    public static void main(String[] args) {
11
12        String input = "Hello";
13        String result = convertStringToBinary(input);
14
15        System.out.println(result);
16
17        // pretty print the binary format
18        System.out.println(prettyBinary(result, 8, " "));
19
20    }
21
22    public static String convertStringToBinary(String input) {
23
24        StringBuilder result = new StringBuilder();
25        char[] chars = input.toCharArray();
26        for (char aChar : chars) {
27            result.append(
28                    String.format("%8s", Integer.toBinaryString(aChar))   // char -> int, auto-cast
29                            .replaceAll(" ", "0")                         // zero pads
30            );
31        }
32        return result.toString();
33
34    }
35
36    public static String prettyBinary(String binary, int blockSize, String separator) {
37
38        List<String> result = new ArrayList<>();
39        int index = 0;
40        while (index < binary.length()) {
41            result.add(binary.substring(index, Math.min(index + blockSize, binary.length())));
42            index += blockSize;
43        }
44
45        return result.stream().collect(Collectors.joining(separator));
46    }
47}
48