Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

change string into binary uding java


package com.mkyong.crypto.bytes;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class StringToBinaryExample1 {

    public static void main(String[] args) {

        String input = "Hello";
        String result = convertStringToBinary(input);

        System.out.println(result);

        // pretty print the binary format
        System.out.println(prettyBinary(result, 8, " "));

    }

    public static String convertStringToBinary(String input) {

        StringBuilder result = new StringBuilder();
        char[] chars = input.toCharArray();
        for (char aChar : chars) {
            result.append(
                    String.format("%8s", Integer.toBinaryString(aChar))   // char -> int, auto-cast
                            .replaceAll(" ", "0")                         // zero pads
            );
        }
        return result.toString();

    }

    public static String prettyBinary(String binary, int blockSize, String separator) {

        List<String> result = new ArrayList<>();
        int index = 0;
        while (index < binary.length()) {
            result.add(binary.substring(index, Math.min(index + blockSize, binary.length())));
            index += blockSize;
        }

        return result.stream().collect(Collectors.joining(separator));
    }
}
Comment

PREVIOUS NEXT
Code Example
Java :: how to convert milliseconds into second in android studio 
Java :: tableau de classe java 
Java :: How to determine if a binary tree has a certain root to leaf target sum value, in Java? 
Java :: convert char to string in java 
Java :: java length of matrix 
Java :: activitycompat.requestpermissions not working 
Java :: sum of a list using for loop in dart 
Java :: java int 
Java :: java copy file 
Java :: string length in java 
Java :: how to cast from int to string java 
Java :: Failed to collect dependencies at net.sf.jasperreports:jasperreports:jar:6.2.0 
Java :: java how to convert string to int 
Java :: list files in directory java 
Java :: enum with numbers java 
Java :: playerhead command minecraft 
Java :: Simple gui in java 
Java :: export java_home linux 
Java :: factors 
Java :: java mongodb find with multiple conditions 
Java :: volley library 
Java :: java type casting 
Java :: java integer division tofloat 
Java :: java files 
Java :: set textView.android:drawableEnd programmatically 
Java :: java formatted output 
Java :: string to int in java 
Java :: spring boot MVC config 
Java :: java object to int 
Java :: json array to list in java 
ADD CONTENT
Topic
Content
Source link
Name
4+5 =