How to Convert a String value to Binary String in java [duplicate] - java

This question already has answers here:
Convert A String (like testing123) To Binary In Java [closed]
(10 answers)
Closed 9 years ago.
I need to convert a String value into Binary format.
For Example:
String str = "Java";
now i want to get it in binary format.how could i do this?
any one could please help me!
Thanks in advane

Try this,
byte[] infoBin = null;
infoBin = "Java".getBytes("UTF-8");
for (byte b : infoBin) {
System.out.println("c:" + (char) b + "-> "
+ Integer.toBinaryString(b));
}
See this link : String to binary output in Java

Try this
byte[] bytes = str.getBytes(charSetName);
this encodes str into a sequence of bytes using the named charset, storing the result into a byte array.

string have getBytes() method.
str.getBytes();

following will give you byte code;
String str = "Java";
byte[] bytecode=str.getBytes();

Related

Convert String.getBytes[].toString To byte[] [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have a problem converting strings to bytes. My problem is this:
String hello = "hello";
byte[] bytes = hello.getBytes();
String byteString = bytes.toString();
Now I want to convert this string to byte[].
and finally get "hello"
Thank you for your help
When you need byte[] to String, use new String(yourArray)
When you need String to byte[], use yourString.getBytes()
String hello = "hello";
byte[] bytes = hello.getBytes();
String byteString = new String(bytes);
System.out.println("byteString: " + byteString); // byteString: hello
byte[] newArray = byteString.getBytes();
String otherString = new String(newArray);
System.out.println("otherString: " + otherString); // otherString: hello
The "toString()" of byte array is the "toString()" inheritance from Object.
The method is:
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
So, it is the reason for... if you call: yourArray.toString() returns something like [B#dcf3e99
I got the answers to my questions. Thank you all for the tips and even those who gave negative feedback to my questions.
The best way to send a string in bytes and get it in bytes is to encode to base64 and get the decode on the other side.
String hello = "hello";
byte[] bytes = hello.getBytes();
String encode = com.sun.org.apache.xerces.internal.impl.dv.util.Base64.encode(bytes );
byte[] decode = com.sun.org.apache.xerces.internal.impl.dv.util.Base64.decode(encode);
System.out.println(new String(decode));
I solved my problem this way, I hope it will be useful for someone who has encountered this problem.
Thanks everyone

Converting byte array to String Java

I wish to convert a byte array to String but as I do so, my String has 00 before every digit got from the array.
I should have got the following result: 49443a3c3532333437342e313533373936313835323237382e303e
But I have the following:
Please help me, how can I get the nulls away?
I have tried the following ways to convert:
xxxxId is the byteArray
String xxxIdString = new String(Hex.encodeHex(xxxxId));
Thank you!
Try something like this:
String s = new String(bytes);
s = s.replace("\0", "")
It's also posible, that the string will end after the first '\0' received, if thats the case, first iterate through the array and replace '\0' with something like '\n' and do this:
String s = new String(bytes);
s = s.replace("\n", "")
EDIT:
use this for a BYTE-ARRAY:
String s = new String(bytes, StandardCharsets.UTF_8);
use this for a CHAR:
String s = new String(bytes);
Try below code:
byte[] bytes = {...}
String str = new String(bytes, "UTF-8"); // for UTF-8 encoding
please have a look here- How to convert byte array to string and vice versa?
In order to convert Byte array into String format correctly, we have to explicitly create a String object and assign the Byte array to it.
String example = "This is an example";
byte[] bytes = example.getBytes();
String s = new String(bytes);

How to convert a string to another so that specific characters aren't allowed in the output?

I have a constraint: I cannot save some chars (like & and =) in a some special storage.
The problem is that I have strings (user input) that contain these not allowed special chars, which I'd like to save to that storage .
I'd like to convert such string to another string that wouldn't contain these special characters.
I'd like to still be able to convert back to the original string without creating ambiguity.
Any idea how to implement the de/convert? Thanks.
Convert the user input to Hex and save. And convert the hex value back to string. Use these methods.
public static String stringToHex(String arg) {
return String.format("%x", new BigInteger(1, arg.getBytes(Charset.forName("UTF-8"))));
}
public static String hexToString(String arg) {
byte[] bytes = DatatypeConverter.parseHexBinary(arg);
return new String(bytes, Charset.forName("UTF-8"));
}
Usage:
String h = stringToHex("Perera & Sons");
System.out.println(h);
System.out.println(hexToString(h));
OUTPUT
506572657261202620536f6e73
Perera & Sons
Already pointed out in the comments but URL Encoding looks like the way to go.
In Java done simply URLEncoder and URLDecoder
String encoded = URLEncoder.encode("My string &with& illegal = characters ", "UTF-8");
System.out.println("Encoded String:" + encoded);
String decoded = URLDecoder.decode(encoded, "UTF-8");
System.out.println("Decoded String:" + decoded);
URLEncoder
URLDecoder

String to byte[] and byte[] to String [duplicate]

This question already has answers here:
How to convert String into Byte and Back
(2 answers)
How do you convert binary data to Strings and back in Java?
(4 answers)
Closed 7 years ago.
I'm dealing with some code that converts a String into a byte[], then from byte[] to String (a String which is a binary representation of the original String), then I'm supposing to do something with that String. When I try to convert the String to byte[] and byte[] to the original String, something is not working.
byte[] binary = "Example".getBytes(StandardCharsets.UTF_8);
String x = new String();
for(byte b : binary)
{
x += Integer.toBinaryString(b);
}
byte[] b = new byte[x.length()];
for (int i = 0; i < b.length; i++)
{
b[i] = (byte) (x.charAt(i) - '0');
}
String str = new String(b, StandardCharsets.UTF_8);
System.out.println(str);
As you can see in that code, I'm using an example String called "Example" and I'm trying to do what I wrote above.
When I print str, I'm not getting that "Example" string.
Does anyone know a way to do this? I searched for a solution on Stack Overflow itself, but I can't figure out a solution.
This should work without the middle section.
byte[] binary = "Example".getBytes(StandardCharsets.UTF_8);
String str = new String(binary, StandardCharsets.UTF_8);
System.out.println(str);

Convert from byte array to string and string to byte array in java [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Conversion of byte[] into a String and then back to a byte[]
I have the following piece of code, I'm trying to get the test to pass, but can't seem to get my head around the various forms of encoding that go on in the java world.
import java.util.Arrays;
class Test {
static final byte[] A = { (byte)0x11, (byte)0x22, (byte)0x33, (byte)0x44, (byte)0x55, (byte)0x66, (byte)0x77, (byte)0x88, (byte)0x99, (byte)0x00, (byte)0xAA };
public static void main(String[] args) {
String s = new String(A);
byte[] b = s.getBytes();
if (Arrays.equals(A,b)) {
System.out.println("TEST PASSED!");
}
else {
System.out.println("TEST FAILED!");
}
}
}
I guess my question is: What is the correct way to convert a byte array of arbitary bytes to a Java String, then later on convert that same Java String to another byte array, which will have the same length and same contents as the original byte array?
Try a specific encoding:
String s = new String(A, "ISO-8859-1");
byte[] b = s.getBytes("ISO-8859-1");
ideone link
Use Base64.
Apache Commons Codec has a Base64 class which supports the following interface:
String str = Base64.encodeBase64String(bytes);
byte[] newBytes = Base64.decodeBase64(str);

Categories