如何将字节数组转换为字符串,反之亦然? [英] How to convert byte array to string and vice versa?

查看:46
本文介绍了如何将字节数组转换为字符串,反之亦然?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在 Android 中将字节数组转换为字符串,但我的字节数组包含负值.

I have to convert a byte array to string in Android, but my byte array contains negative values.

如果我再次将该字符串转换为字节数组,我得到的值与原始字节数组值不同.

If I convert that string again to byte array, values I am getting are different from original byte array values.

我该怎么做才能获得正确的转换?我用来进行转换的代码如下:

What can I do to get proper conversion? Code I am using to do the conversion is as follows:

// Code to convert byte arr to str:
byte[] by_original = {0,1,-2,3,-4,-5,6};
String str1 = new String(by_original);
System.out.println("str1 >> "+str1);

// Code to convert str to byte arr:
byte[] by_new = str1.getBytes();
for(int i=0;i<by_new.length;i++) 
System.out.println("by1["+i+"] >> "+str1);

我被这个问题困住了.

推荐答案

你的字节数组必须有一些编码.如果您有负值,则编码不能是 ASCII.一旦你弄清楚了,你可以使用以下方法将一组字节转换为字符串:

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

您可以使用一堆编码,请查看Oracle javadocs.

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

这篇关于如何将字节数组转换为字符串,反之亦然?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆