Convert strings to binary [Java]

Let's say I have the following line:

String s = "Hello, stackoverflow"

How would I convert this to a binary number (0s and 1s)? Here's the trick: I'm not allowed to use built-in methods for conversion. This should be done mathematically. I don’t know where to start. Can someone point me in the right direction?

Edit 1: I saw this question , and people suggested using getBytes (string), charset UTF-8, and Integer.toBinaryString. I am not allowed to use any of these methods for conversion. I have not heard about the 36th base either.

+4
source share
3 answers

, getByte(), Integer.toBinaryString(byte). .

: ~ , Integer.toBinaryString(byte) int ( .), ( .)

: ~ , parse char char, char ascii .

int tempChar = (int)ch;

.

Integer.toString(tempChar,2);

.

string finalString = "";
for(int i = 0;i<myStr.length;i++){
    int tempChar = (int)ch;
    finalString = finalString + Integer.toString(tempChar,2);//& this is not allowed then now only you need to create function for integer to binary conversion.
}
System.out.println("Your byte String is"+finalString);
+2

: -

String s = "Hello, stackoverflow"
byte[] bytes = str.getBytes(s);

getBytes() java

, , .

, . CharsetEncoder .

:

for(int i=0; i<array.length;i++){
    System.out.println(Integer.toBinaryString(0x100 + array[i]).substring(1));
}
+1

, :

byte[] b = s.getBytes();

, , :

String#charAt(int):

String s = "Hello, stackoverflow";
StringBuilder buf = new StringBuilder();
for (int i = 0; i < s.length(); i++ ) {
    int charcterASCII = s.charAt(i);
    // Automatic type casting as 'char' is a type of 'int'
    buf.append(Integer.toBinaryString(characterASCII);
    // or:
    // buf.append(characterASCII, 2);
    // or - custom method:
    // buf.append(toBinary(characterASCII));
}
System.out.println("answer : " + buf.toString());

toBinary(int), :

public static final String toBinary (int num) {
    char[] buf = new char[32];
    int charPos = 32;
    do {
        buf[--charPos] = i & 1;
        i >>>= 1;
    } while (i != 0);
    return new String(buf);
}

, , .: -)

+1

Source: https://habr.com/ru/post/1534187/


All Articles