The usual way is to use String#getBytes() to get the underlying bytes and then present those bytes in some other form (hex, binary whatever).

Note that getBytes() uses the default charset, so if you want the string converted to some specific character encoding, you should use getBytes(String encoding) instead, but many times (esp when dealing with ASCII) getBytes() is enough (and has the advantage of not throwing a checked exception).

For specific conversion to binary, here is an example:

  String s = "foo";
  byte[] bytes = s.getBytes();
  StringBuilder binary = new StringBuilder();
  for (byte b : bytes)
  {
     int val = b;
     for (int i = 0; i < 8; i++)
     {
        binary.append((val & 128) == 0 ? 0 : 1);
        val <<= 1;
     }
     binary.append(' ');
  }
  System.out.println("'" + s + "' to binary: " + binary);

Running this example will yield:

'foo' to binary: 01100110 01101111 01101111 
Answer from Nuoji on Stack Overflow
🌐
Mkyong
mkyong.com › home › java › java – convert string to binary
Java – Convert String to Binary | mkyong.com
June 9, 2020 - We can use Unicode to represent non-English characters since Java String supports Unicode, we can use the same bit masking technique to convert a Unicode string to a binary string.
Discussions

Converting a string to binary [Java] - Stack Overflow
Let's say I have the following string: String s = "Hello, stackoverflow" How would I convert that into a binary number (0s and 1s)? Here's the trick: I'm not allowed to use built-in methods for the More on stackoverflow.com
🌐 stackoverflow.com
Help converting String to Binary in Java ..
it will only print out the first word Read the documentation for the next() method of the java.util.Scanner class: http://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#next-- The next() method returns only the next token (e.g., a single word). If that is not the behavior that you want, then why are you using the next() method? print out an extra 0 at the front of every set of 1,0's Yes, the most significant bit in all of the bytes you are probably reading is 0. Are you expecting something different? More on reddit.com
🌐 r/learnprogramming
2
1
February 22, 2015
Convert String to Binary
string.getBytes(); More on reddit.com
🌐 r/learnjava
4
3
February 11, 2022
String to binary output in Java - Stack Overflow
I want to get binary (011001..) from a String but instead i get [B@addbf1 , there must be an easy transformation to do this but I don't see it. More on stackoverflow.com
🌐 stackoverflow.com
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › convert-string-binary-sequence
Convert String into Binary Sequence - GeeksforGeeks
// C++ program to convert // string into binary string #include <bits/stdc++.h> using namespace std; // utility function void strToBinary(string s) { int n = s.length(); for (int i = 0; i <= n; i++) { // convert each char to // ASCII value int val = int(s[i]); // Convert ASCII value to binary string bin = ""; while (val > 0) { (val % 2)? bin.push_back('1') : bin.push_back('0'); val /= 2; } reverse(bin.begin(), bin.end()); cout << bin << " "; } } // driver code int main() { string s = "geeks"; strToBinary(s); return 0; } ... // Java program to convert // string into binary string import java.ut
Published: August 4, 2022
Top answer
1 of 3
3

This seems a bit unfair because we can't use:

byte[] b = s.getBytes();

This is the shortest solution to your problem, but since you aren't supposed to use that, here's a bad approach:

Using String#charAt(int):

String s = "Hello, stackoverflow";
StringBuilder buf = new StringBuilder();
for (int i = 0; i < s.length(); i++ ) {
    int characterASCII = 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());

And if you decide to use toBinary(int) method, here it is:

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);
}

Or if even this is not allowed, you'd better make your own solution. :-)

2 of 3
2

First get bytes form string using getByte() function then use Integer.toBinaryString(byte) function. & thats it.

NOTE:~ Make sure Integer.toBinaryString(byte) accepts int(or in this case byte not all.) so you have to pass byte by byte.(may be for loop.)

Edited :~ what you can do is parse string char by char & for each char you can get ascii value using.

int tempChar = (int)ch;

Then simpley use this.

Integer.toString(tempChar,2);

try this.

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);
🌐
Reddit
reddit.com › r/learnprogramming › help converting string to binary in java ..
r/learnprogramming on Reddit: Help converting String to Binary in Java ..
February 22, 2015 -

I know i posted a similar question before but I wasn't very happy with the answers (my fault for asking the question wrong) but I have code now.. I'm trying to convert a user inputted string into binary code .. With my code, if i type in a sentece with spaces it will only print out the first word AND print out an extra 0 at the front of every set of 1,0's Anybody have any way to fix this or any better code to actually convert (I've been looking online for hours!)

 import java.util.Scanner;
 public class xyz{
     public static void main(String[] args){
         System.out.println("Enter the string you want printed : ");
         Scanner sc = new Scanner(System.in);
         String s = sc.next();
 
         byte[] bytes = s.getBytes();
         StringBuilder binary = new StringBuilder();
         for (byte b : bytes){
             int val = b;
             for (int i = 0; i < 8; i++){
                 binary.append((val & 128) == 0 ? 0 : 1);
                 val <<= 1;
             }
             binary.append(' ');
         }
         System.out.println("'" + s + "' to binary: " + binary);
     }
 }
🌐
Code2care
code2care.org › home › java › java: convert string to binary
Java: Convert String to Binary | Code2care
June 29, 2023 - package org.code2care.java.examples; public class ConvertStringToBinary { public static void main(String[] args) { String userString = "Hello World!"; StringBuilder binaryStringBuilder = new StringBuilder(); for (char ch : userString.toCharArray()) { String binary = Integer.toBinaryString(ch); binaryStringBuilder.append(String.format("%8s", binary).replace(' ', '0')); } System.out.println(binaryStringBuilder.toString()); } } Output:
🌐
Techie Delight
techiedelight.com › home › java › convert a string to binary in java
Convert a String to binary in Java | Techie Delight
July 7, 2026 - The easiest way to convert a string to binary in Java is to use the built-in Integer.toBinaryString() method, which returns binary representation of an integer as a string. The idea is to convert a string into a char array.
Find elsewhere
🌐
Reddit
reddit.com › r/learnjava › convert string to binary
r/learnjava on Reddit: Convert String to Binary
February 11, 2022 -

Here's the beginning of my code (far from completed), a hash function I'm making.

public int hashCode(){
int hashValue = 0;
String fixedISBN = getIsbn().toString().replace("-", ""); 
fixedISBN = fixedISBN.substring(fixedISBN.length()-4, fixedISBN.length()); 
return hashValue;
 }

As part of my hash function, I need to get the binary representation of fixedISBN and I don't know how to do that.

🌐
Sololearn
sololearn.com › en › Discuss › 2486340 › how-to-make-string-to-binary-converter-usi-g-java
How to make string to binary converter usi g java? | Sololearn: Learn to code for FREE!
September 8, 2020 - So you can get these codes and convert them to binary. Like this : String name = "Kim"; char[] array = name.toCharArray(); StringBuilder sb = new StringBuilder(); for(int i= 0; i< array.length; i++) { String result = Integer.toBinaryString((int) array[i]); String formattedResult = String.format("%8s", result).replaceAll(" ", "0"); sb.append(formattedResult); sb.append(" "); } System.out.println(sb.toString()); So basically we want to divide a string to separate characters.
🌐
Coderanch
coderanch.com › t › 662356 › java › Java-convert-String-binary
Java convert a String to binary, question (Java in General forum at Coderanch)
February 21, 2016 - Why does this convert a number to a binary sequence? Because it always checks the same bit position. Take 'C' (67), which is · 01000011 so the first time you '&' it with 128, which is (as you already worked out) 10000000 you get 00000000 which equals 0, so you add '0' to the string.
🌐
Educative
educative.io › answers › how-to-convert-an-integer-to-binary-in-java
How to convert an integer to binary in Java
To convert an integer to binary, we can simply call thepublic static String toBinaryString(int i) method of the Integer class.
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-lang-integer-tobinarystring-method
Java lang.Integer.toBinaryString() method - GeeksforGeeks
December 5, 2018 - The java.lang.Integer.toBinaryString() method returns a string representation of the integer argument as an unsigned integer in base 2. It accepts an argument in Int data-type and returns the corresponding binary string.
Top answer
1 of 2
7

I would change

public int getDecimal(char character)
{
    for (int i = 0; i <= 255; i++)
    {
         if (character == (char) i)
         {
              return i;
          }
     }
     return -1;
}

To just

public int getDecimal(char character)
{
     if(character<0||character>255)
          return -1;
     return character;
}

, As char is a number, too.

Also try using >> operator to get nth binary digit, which means division by 2.

number = (int) (number / 2);

To

number = number >>1;

I don't know if it would be faster in java, but it works faster in old computer's assembly program(Division was expensive than just shifting)

If you use assembly you can access carry flags and optimize it.

For more information about it, refer here.

Provided that al holds the target number and bx holds the target string address, and cx holds 8,

L1:                  ; This is the loop
mov dl, '0'      ; Ascii character zero
shl al, 1          ; Upper bit now in carry flag
adc dl, 0        ; Adds carry flag - 0 or 1
mov [bx], dl   ; Save digit to current position
inc bx             ; Next position
loop L1          ; Counts down cx
mov [bx], 0    ; Zero terminate (might need to use register)
2 of 2
2

Here is my final working code

for (int i = 0; i < characters.length; i++) {
    int number = getDecimal(characters[i]);
    for (int j = 0; j < 8; j++) {
        result.insert(i * 9, (number % 2 == 0) ? 0 : 1);
        number = (int) (number >> 1);
    }
    // put a space if it isn't the last string
    if (i < characters.length - 1)
        result.insert(8 * (i + 1) + i, " ");
}

public int getDecimal(char character) {
    return character;
}

What I did?

  • I initialized the integer variable number inside the loop. I dunno why, just wanted to do it, think it is more organized now.
  • I used conditional operator known as Ternary Operator instead of the if/else. Reason is because it is shorter and looks more neat.
  • Made it put the bit at the beginning (first index) and after the loop runs, it puts a space at the end (after the last character).
  • Used the shifting operator instead of the division as recommended below, may be faster.
  • Why i*9 for the first loop? Cause i will start of with 0, so it is always going to put the character in the index 0. Then when i increments and becomes 1, it is going to be 9. Here if you realize, the 8 bits take the positions 0,7 then space at 8 and the new word binary sequence starts at 9. Therefore, the printing is (8 * (i+1)) for a loop for 3, will give 8, 17, 26 which is where we need the spaces.
  • Changed the get decimal number from ASCII character function and made it shorter by just returning the decimal of the character. No need for the if statements or for loops.

I made a simple debug for those of you who are confused or don't get it after the insert method add this

System.out.println("j:" + j + " Current number? " + number + " remainder is " + number % 2);

Output:

i:0

j:0 Current number? 97 remainder is 1

j:1 Current number? 48 remainder is 0

j:2 Current number? 24 remainder is 0

j:3 Current number? 12 remainder is 0

j:4 Current number? 6 remainder is 0

j:5 Current number? 3 remainder is 1

j:6 Current number? 1 remainder is 1

j:7 Current number? 0 remainder is 0

Binary code for a is 01100001

If there are further improvements or notes, please let me know, and ask if you have questions. Thanks everyone!

🌐
Spiceworks
community.spiceworks.com › programming & development
Java String to Binary conversion - Programming & Development - Spiceworks Community
March 11, 2010 - Hi all, I am having some hexadecimal value in string or byte array, i want to convert that hexadecimal value to binary. Ex: String hex=““ABCD””; byte bb={65,66,67,68};// ASCII values of the A,B,C,D I want output as "“101…
🌐
Code Beautify
codebeautify.org › string-binary-converter
String to Binary Converter Online tool
Translate String to Binary is a very unique tool to convert String numbers, a combination of 0-9 and A-F to Binary.
🌐
Coderanch
coderanch.com › t › 394839 › java › String-Binary
String to Binary? (Beginning Java forum at Coderanch)
November 11, 2003 - Travis, You break the String down into an array of char by calling getChar() on it. You can then get the int value of each char using the Integer.toBinaryString() method to convert each char to a binary String representation as in the following code fragment: Is this what you are trying to do ?