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 OverflowThe 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
A shorter example
private static final Charset UTF_8 = Charset.forName("UTF-8");
String text = "Hello World!";
byte[] bytes = text.getBytes(UTF_8);
System.out.println("bytes= "+Arrays.toString(bytes));
System.out.println("text again= "+new String(bytes, UTF_8));
prints
bytes= [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]
text again= Hello World!
Converting a string to binary [Java] - Stack Overflow
Help converting String to Binary in Java ..
Convert String to Binary
String to binary output in Java - Stack Overflow
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. :-)
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);
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);
}
}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.
Only Integer has a method to convert to binary string representation check this out:
import java.io.UnsupportedEncodingException;
public class TestBin {
public static void main(String[] args) throws UnsupportedEncodingException {
byte[] infoBin = null;
infoBin = "this is plain text".getBytes("UTF-8");
for (byte b : infoBin) {
System.out.println("c:" + (char) b + "-> "
+ Integer.toBinaryString(b));
}
}
}
would print:
c:t-> 1110100
c:h-> 1101000
c:i-> 1101001
c:s-> 1110011
c: -> 100000
c:i-> 1101001
c:s-> 1110011
c: -> 100000
c:p-> 1110000
c:l-> 1101100
c:a-> 1100001
c:i-> 1101001
c:n-> 1101110
c: -> 100000
c:t-> 1110100
c:e-> 1100101
c:x-> 1111000
c:t-> 1110100
Padding:
String bin = Integer.toBinaryString(b);
if ( bin.length() < 8 )
bin = "0" + bin;
Arrays do not have a sensible toString override, so they use the default object notation.
Change your last line to
return Arrays.toString(infoBin);
and you'll get the expected output.
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)
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*9for 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!
Use this:
System.out.println(Integer.toBinaryString(Integer.parseInt("000",2))); // gives 0
System.out.println(Integer.toBinaryString(Integer.parseInt("010",2))); // gives 10
System.out.println(Integer.toBinaryString(Integer.parseInt("100",2))); // gives 100
Maybe you want this:
int i = Integer.valueOf(binary, 2); // ie base 2
This call expects the input to be a string of 0 and 1 chars.
Then if you want an array of bytes:
byte[] bytes = new ByteBuffer().putInt(i).compact().array();
Sure, you may speed up your code execution. But the core problem remains: Inresponsive UI executing a long running task.
If you expect the user wait for completion a long running task you should consider UI supported synchronized mechanisms to adress it.
Asynchronous execution is mentioned here:
http://docs.oracle.com/javafx/2/threads/jfxpub-threads.htm
The idea is: Execute your code in a separate thread and synchronize results by publishing them through the Java FX thread.
JavaFX Nodes runs on a separate UI Thread and this Thread should never be used other than to update the UI Components.. Always use a separate Thread to do the operations not related to UI. see this PrimeFinder Example.
And here is my version of your binaryToText
private static String binaryToText(String input) {
if (input.length() % 8 != 0) {
throw new IllegalArgumentException("input must be a multiple of 8");
}
StringBuilder result = new StringBuilder();
for (int i = 0; i <input.length(); i+=8) {
int charCode = Integer.parseInt(input.substring(i,i+8), 2);
result.append((char) charCode);
}
return result.toString();
}
You Can Try This:
String[] singleBinaryArray = binary.toString().split("\\s");
String finalResult = "";
for (String string : singleBinaryArray) {
Character c = (char) Integer.parseInt(string, 2);
finalResult += c.toString();
}
System.out.println("String " + finalResult);
The solution you are looking for is as below:
String[] bytesStr = binary.toString().split(" ");
for(String c : bytesStr){
System.out.print((char)Byte.parseByte(c,2));
}
The "binary" value you have is in reality the binary in string format. So convert it to a byte by using parseByte with a radix (base) of 2.
The above program prints Milind