String to byte[] and byte[] to String [duplicate] - java

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

Related

Base64 Failed to Decode String to Byte Array

I tried to decode a string to byte array using Base64. But it returned null. Here is the code:
LZW lzw = new LZW();
String enkripEmbedFileString = Base64.encode(byteFile);
List<Short> compressed = lzw.compress(enkripEmbedFileString);
String kompress = "";
Iterator<Short> compressIterator = compressed.iterator();
while (compressIterator.hasNext()) {
String sch = compressIterator.next().toString();
int in = Integer.parseInt(sch);
char ch = (char) in;
kompress = kompress + ch;
}
byteFile = Base64.decode(kompress);
I call "byteFile" variable at the last row in a code below this code and it throw NullPointerException.
I have check the "kompress" variable and it's not null. It contains a string.
All you need to know is, with that code I compress a string with LZW which require String for parameter and returns List<Short>. And, I convert the List<Short> to a String with a loop that you can see.
The problem is, why Base64 failed to convert String to byte[], after that String modified with LZW?
Whereas, if I decompress the String first and than return the decompressed String to be converted with Base64 to byte[], has no problem. It works. Here is the code which works:
//LZW Compress
LZW lzw = new LZW();
String enkripEmbedFileString = Base64.encode(byteFile);
List<Short> compressed = lzw.compress(enkripEmbedFileString);
String kompress = "";
Iterator<Short> compressIterator = compressed.iterator();
while (compressIterator.hasNext()) {
String sch = compressIterator.next().toString();
int in = Integer.parseInt(sch);
char ch = (char) in;
kompress = kompress + ch;
}
//Decompress
List<Short> kompressback = back(kompress);
String decompressed = decompress(kompressback);
byteFile = Base64.decode(decompressed);
Please, give me an explanation. Where is my fault?
Base64 decode can be applied only to strings that contain Base64 encoded data. Since you encode and then compress, the result is not Base64. You proved it yourself when you saw that uncompressing the data first allowed you to then decode the Base64 string.

Java How to read unicode characters in socket? [duplicate]

This question already has an answer here:
DataInputStream and UTF-8
(1 answer)
Closed 9 years ago.
The server receives byte array as inputstream,and I wrapped the stream with DataInputStream.The first 2 bytes indicate the length of the byte array,and the second 2 bytes indicate a flag,and the next bytes consist of the content.My problem is the content contains unicode character which has 2 bytes.How can I read the unicode char ? My prev code is:
DataInputStream dis = new DataInputStream(is);
int length = dis.readUnsignedShort();
int flag = dis.readUnsignedShort();
String content = "";
int c;
for (int i = 0; i < length - 4; i++) {
c = dis.read();
content += (char) c;
}
It only can read ascII.thxs for your helps!
This depends on encoding scheme of your input. If you do not want to do the heavy-lifting, you could use Apache IOUtils and convert the bytes to unicode string.
Example :
IOUtils.toString(bytes, "UTF-8")

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

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

String to bytes to string

The question is in comments in the code, I thought that'd be an easier way to ask...
Easy question, but I can't seem to find an answer. I want to convert a String to it's byte[] (easy, String.getBytes()). Then I want to convert a String of bytes (101011010101001 for example) to a byte[] and get the String value of that (that's easy too: new String(byte[]))
Here's what I've got so far:
Scanner scan = new Scanner(System.in);
String string = scan.nextLine();
String byteString = "";
for (byte b : string.getBytes()) {
byteString += b;
}
System.out.println(byteString);
//This isn't exactly how it works, these two parts in separate methods, but you get the idea...
String byteString = scan.nextLine();
byte[] bytes = byteString.literalToBytes() //<== or something like that...
//The line above is pretty much all I need...
String string = new String(bytes);
System.out.println(string);
This won't work. The problem is that when you convert your bytes to a string you are going to get a string like
2532611134
So analyzing this string, is the first byte 2, or 25, or 253?
The only way to make this work would be to use a DecimalFormat and make sure every byte is 3 characters long in your string
EDIT
Please see this answer for a solution.
With this you can:
String string = scan.nextLine();
String convertByte = convertByte(string.getBytes());
System.out.println(convertByte);
String byteString = scan.nextLine();
System.out.println(new String(convertStr(byteString)));
Alright, because the commenter who pointed me to this question (which lead me to this answer) isn't going to answer, I'll just post the solution here:
Scanner scan = new Scanner(System.in);
String pass = scan.nextLine();
StringBuilder byteString = new StringBuilder();
for (byte b : pass.getBytes()) {
b = (byte) (b);
byteString.append(b).append(","); //appending that comma is what does the trick.
}
System.out.println(byteString);
//
String[] split = byteString.toString().split(","); //splitting by that comma is what does the trick... too...
byte[] bytes = new byte[split.length];
for (int i = 0; i < split.length; i++) {
bytes[i] = (byte) (Byte.valueOf(split[i]).byteValue());
}
System.out.println(new String(bytes));
I guess what you want is this
// to get back the string from byte array
StringBuilder byteString = new StringBuilder();
for (byte b : string.getBytes()) {
byteString.append((char)b);
}
System.out.println(byteString.toString());
// to get the binary representation from string
StringBuilder byteString = new StringBuilder();
for (byte b : string.getBytes()) {
System.out.print(Integer.toBinaryString((int)b));
}
System.out.println(byteString.toString());

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