Convert string to byte and byte to string in java

Convert a String to a byte array and then back to the original String

Is it possible to convert a string to a byte array and then convert it back to the original string in Java or Android? My objective is to send some strings to a microcontroller (Arduino) and store it into EEPROM (which is the only 1 KB). I tried to use an MD5 hash, but it seems it’s only one-way encryption. What can I do to deal with this issue?

Try using SHA128 if you’re sending the string to an adruino. It’s reversible; but I don’t know if you’d need that code on the arduino.

5 Answers 5

I would suggest using the members of string, but with an explicit encoding:

byte[] bytes = text.getBytes("UTF-8"); String text = new String(bytes, "UTF-8"); 

By using an explicit encoding (and one which supports all of Unicode) you avoid the problems of just calling text.getBytes() etc:

  • You’re explicitly using a specific encoding, so you know which encoding to use later, rather than relying on the platform default.
  • You know it will support all of Unicode (as opposed to, say, ISO-Latin-1).

EDIT: Even though UTF-8 is the default encoding on Android, I’d definitely be explicit about this. For example, this question only says «in Java or Android» — so it’s entirely possible that the code will end up being used on other platforms.

Basically given that the normal Java platform can have different default encodings, I think it’s best to be absolutely explicit. I’ve seen way too many people using the default encoding and losing data to take that risk.

EDIT: In my haste I forgot to mention that you don’t have to use the encoding’s name — you can use a Charset instead. Using Guava I’d really use:

byte[] bytes = text.getBytes(Charsets.UTF_8); String text = new String(bytes, Charsets.UTF_8); 

Источник

How to convert Java String into byte[]?

The second is an address. Is there anything I’m doing wrong? I need the result in a byte[] to feed it to gzip decompressor, which is as follows.

String decompressGZIP(byte[] gzip) throws IOException < java.util.zip.Inflater inf = new java.util.zip.Inflater(); java.io.ByteArrayInputStream bytein = new java.io.ByteArrayInputStream(gzip); java.util.zip.GZIPInputStream gzin = new java.util.zip.GZIPInputStream(bytein); java.io.ByteArrayOutputStream byteout = new java.io.ByteArrayOutputStream(); int res = 0; byte buf[] = new byte[1024]; while (res >= 0) < res = gzin.read(buf, 0, buf.length); if (res >0) < byteout.write(buf, 0, res); >> byte uncompressed[] = byteout.toByteArray(); return (uncompressed.toString()); > 

Sorry, I’m trying to convert a String to bytearray and back and getting a wrong result. I’ll edit it in a while and get back.

Читайте также:  Javascript date diff in seconds

Your problem is that String.getBytes() does indeed return a byte array, but your belief that the toString() of a byte array will return a useful result is incorrect.

8 Answers 8

The object your method decompressGZIP() needs is a byte[] .

So the basic, technical answer to the question you have asked is:

byte[] b = string.getBytes(); byte[] b = string.getBytes(Charset.forName("UTF-8")); byte[] b = string.getBytes(StandardCharsets.UTF_8); // Java 7+ only 

However the problem you appear to be wrestling with is that this doesn’t display very well. Calling toString() will just give you the default Object.toString() which is the class name + memory address. In your result [B@38ee9f13 , the [B means byte[] and 38ee9f13 is the memory address, separated by an @ .

For display purposes you can use:

But this will just display as a sequence of comma-separated integers, which may or may not be what you want.

To get a readable String back from a byte[] , use:

String string = new String(byte[] bytes, Charset charset); 

The reason the Charset version is favoured, is that all String objects in Java are stored internally as UTF-16. When converting to a byte[] you will get a different breakdown of bytes for the given glyphs of that String , depending upon the chosen charset.

Источник

String to byte array, byte array to String in Java

String to byte array, byte array to String in Java

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Today we will learn how to convert String to byte array in java. We will also learn how to convert byte array to String in Java.

String to byte array

We can use String class getBytes() method to encode the string into a sequence of bytes using the platform’s default charset. This method is overloaded and we can also pass Charset as argument. Here is a simple program showing how to convert String to byte array in java.

package com.journaldev.util; import java.util.Arrays; public class StringToByteArray < public static void main(String[] args) < String str = "PANKAJ"; byte[] byteArr = str.getBytes(); // print the byte[] elements System.out.println("String to byte array: " + Arrays.toString(byteArr)); >> 

java string to byte array, string to byte array in java

Below image shows the output when we run the above program. We can also get the byte array using the below code.

byte[] byteArr = str.getBytes("UTF-8"); 

However if we provide Charset name, then we will have to either catch UnsupportedEncodingException exception or throw it. Better approach is to use StandardCharsets class introduced in Java 1.7 as shown below.

byte[] byteArr = str.getBytes(StandardCharsets.UTF_8); 

Java byte array to String

package com.journaldev.util; public class ByteArrayToString < public static void main(String[] args) < byte[] byteArray = < 'P', 'A', 'N', 'K', 'A', 'J' >; byte[] byteArray1 = < 80, 65, 78, 75, 65, 74 >; String str = new String(byteArray); String str1 = new String(byteArray1); System.out.println(str); System.out.println(str1); > > 

byte array to string in java, convert byte array to string

Below image shows the output produced by the above program. Did you notice that I am providing char while creating the byte array? It works because of autoboxing and char ‘P’ is being converted to 80 in the byte array. That’s why the output is the same for both the byte array to string conversion. String also has a constructor where we can provide byte array and Charset as an argument. So below code can also be used to convert byte array to String in Java.

String str = new String(byteArray, StandardCharsets.UTF_8); 
byte[] byteArray1 = < 80, 65, 78, 75, 65, 74 >; String str = new String(byteArray1, 0, 3, StandardCharsets.UTF_8); 

Above code is perfectly fine and ‘str’ value will be ‘PAN’. That’s all about converting byte array to String in Java. You can checkout more array examples from our GitHub Repository. Reference: getBytes API Doc

Читайте также:  Соурс буст раскрутка серверов css v34

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us

Источник

How to convert String into Byte and Back

For converting a string, I am converting it into a byte as follows: byte[] nameByteArray = cityName.getBytes(); To convert back, I did: String retrievedString = new String(nameByteArray); which obviously doesn’t work. How would I convert it back?

you need to specify the charsetname on new String() , for example new String(byte[], «utf-8»); . Use the same charset as the original string.

That’s how you are supposed to convert it back. eg ideone.com/TDb7E Can you explain exactly what doesn’t work?

Read the canonical essay to understand why you need to specify the encoding when converting bytes to a string.

2 Answers 2

What characters are there in your original city name? Try UTF-8 version like this:

byte[] nameByteArray = cityName.getBytes("UTF-8"); String retrievedString = new String(nameByteArray, "UTF-8"); 

That shouldn’t be the issue since both getBytes() and String(byte[] byteArray) use the default charset which is obviously the same in both cases — assuming he is doing this on single machine though.

@Jan: It would only work if the default character encoding is able to encode all of the characters in the existing text.

Seems like it works but when I do the following: System.out.print(«PTRSP — «); System.out.println(retrievedString); , The first character always that prints out is a 6. So it the above code prints out as: 6TRSP — ??Albuquerque . Also why do I get ?? in the beginning?

That means you have cityName contains some non printable characters? Can you tell me what is character encoding of original string variable cityName? Also dump the char array of original String variable cityName and paste their character codes here.

Читайте также:  Одномерный массив java string

Actually that’s exactly how you do it. The only thing that can go wrong is that you’re implicitly using the platform default encoding, which could differ between systems, and might not be able to represent all characters in the string.

The solution is to explicitly use an encoding that can represent all characts, such as UTF-8:

byte[] nameByteArray = cityName.getBytes("UTF-8"); String retrievedString = new String(nameByteArray, "UTF-8"); 

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.25.43544

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Оцените статью