How to Convert Byte Array to String and Vice Versa

How to convert byte array to string and vice versa?

Your byte array must have some encoding. The encoding cannot be ASCII if you've got negative values. Once you figure that out, you can convert a set of bytes to a String using:

byte[] bytes = {...}
String str = new String(bytes, StandardCharsets.UTF_8); // for UTF-8 encoding

There are a bunch of encodings you can use, look at the supported encodings in the Oracle javadocs.

C# byte array to string, and vice-versa

class Encoding supports what you need, example below assumes that you need to convert string to byte[] using UTF8 and vice-versa:

string S = Encoding.UTF8.GetString(B);
byte[] B = Encoding.UTF8.GetBytes(S);

If you need to use other encodings, you can change easily:

Encoding.Unicode
Encoding.ASCII
...

Converting byte array to String Java

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

How to Convert Byte Array back into string?

If s is that byte string:

for x in s:
print(f'{x:08b}')

Instead of print, you can do what you like with the strings of 0's and 1's.

It is unnecessarily inefficient to go through strings of 0 and 1 characters for encoding and decoding. You should instead assemble and disassemble the bytes directly using the bit operators (<<, >>, |, &).

Converting Byte Array to String and vice versa

You can use apache library's Hex class. It provides decode and encode functions.

String s = "42Gears Mobility Systems";
byte[] bytes = Hex.decodeHex(s.toCharArray());

String s2 = new String(Hex.encodeHex(bytes));

Overhead of converting from []byte to string and vice-versa

In Go, strings are immutable so any change creates a new string. As a general rule, convert from a string to a byte or rune slice once and convert back to a string once. To avoid reallocations, for small and transient allocations, over-allocate to provide a safety margin if you don't know the exact number.

For example,

package main

import (
"bytes"
"fmt"
"unicode"
"unicode/utf8"

"code.google.com/p/go.text/transform"
"code.google.com/p/go.text/unicode/norm"
)

var isMn = func(r rune) bool {
return unicode.Is(unicode.Mn, r) // Mn: nonspacing marks
}

var transliterations = map[rune]string{
'Æ': "AE", 'Ð': "D", 'Ł': "L", 'Ø': "OE", 'Þ': "Th",
'ß': "ss", 'æ': "ae", 'ð': "d", 'ł': "l", 'ø': "oe",
'þ': "th", 'Œ': "OE", 'œ': "oe",
}

func RemoveAccents(b []byte) ([]byte, error) {
mnBuf := make([]byte, len(b)*125/100)
t := transform.Chain(norm.NFD, transform.RemoveFunc(isMn), norm.NFC)
n, _, err := t.Transform(mnBuf, b, true)
if err != nil {
return nil, err
}
mnBuf = mnBuf[:n]
tlBuf := bytes.NewBuffer(make([]byte, 0, len(mnBuf)*125/100))
for i, w := 0, 0; i < len(mnBuf); i += w {
r, width := utf8.DecodeRune(mnBuf[i:])
if s, ok := transliterations[r]; ok {
tlBuf.WriteString(s)
} else {
tlBuf.WriteRune(r)
}
w = width
}
return tlBuf.Bytes(), nil
}

func main() {
in := "test stringß"
fmt.Println(in)
inBytes := []byte(in)
outBytes, err := RemoveAccents(inBytes)
if err != nil {
fmt.Println(err)
}
out := string(outBytes)
fmt.Println(out)
}

Output:

test stringß
test stringss

Java Byte Array to String to Byte Array

You can't just take the returned string and construct a string from it... it's not a byte[] data type anymore, it's already a string; you need to parse it. For example :

String response = "[-47, 1, 16, 84, 2, 101, 110, 83, 111, 109, 101, 32, 78, 70, 67, 32, 68, 97, 116, 97]";      // response from the Python script

String[] byteValues = response.substring(1, response.length() - 1).split(",");
byte[] bytes = new byte[byteValues.length];

for (int i=0, len=bytes.length; i<len; i++) {
bytes[i] = Byte.parseByte(byteValues[i].trim());
}

String str = new String(bytes);

** EDIT **

You get an hint of your problem in your question, where you say "Whatever I seem to try I end up getting a byte array which looks as follows... [91, 45, ...", because 91 is the byte value for [, so [91, 45, ... is the byte array of the string "[-45, 1, 16, ..." string.

The method Arrays.toString() will return a String representation of the specified array; meaning that the returned value will not be a array anymore. For example :

byte[] b1 = new byte[] {97, 98, 99};

String s1 = Arrays.toString(b1);
String s2 = new String(b1);

System.out.println(s1); // -> "[97, 98, 99]"
System.out.println(s2); // -> "abc";

As you can see, s1 holds the string representation of the array b1, while s2 holds the string representation of the bytes contained in b1.

Now, in your problem, your server returns a string similar to s1, therefore to get the array representation back, you need the opposite constructor method. If s2.getBytes() is the opposite of new String(b1), you need to find the opposite of Arrays.toString(b1), thus the code I pasted in the first snippet of this answer.



Related Topics



Leave a reply



Submit