将字节数组转换为字符串 [英] Convert byte array to String
问题描述
如何在BlackBerry中将字节数组转换为字符串?
How do I convert a byte array to a String in BlackBerry?
我用过
new String(bytearray,encoding type);
调用toString()时得到[B@fb5955d6
.有人可以帮忙以BlackBerry可读的格式获取此字符串吗?
I am getting [B@fb5955d6
when calling toString().Can anyone help get this string in a readable format for BlackBerry?
推荐答案
您不会向我们显示此字节数据来自何处 ,或您期望的什么值它拥有.因此,我不确定是否可以完全调试您的问题.但是,希望这会有所帮助:
You don't show us where this byte data is coming from, or what value you expect it to have. So, I'm not sure I can fully debug your problem. But, hopefully this helps:
仅在字节数组上调用toString()
时看到打印出[B@fb5955d6
的原因是打印出数组数据类型的简短代码(例如byte
),然后打印出类似您的 address 的代码(如果您熟悉C/C ++)变量,这几乎是您真正想要的,尤其是在Java中.
The reason you are seeing [B@fb5955d6
printed out when you simply call toString()
on your byte array is that the default implementation of toString() will just print out a short code for the array data type (e.g. byte
), and then something like an address (if you're familiar with C/C++) of your variable, which is almost never what you really want, especially in Java.
当您拥有二进制数据(作为byte[]
)时,Java不知道您是否打算将该数据作为String
,ButtonField
或FuzzyWarble
.因此,打印出来的东西比对象的地址更有意义.
When you have binary data (as a byte[]
), Java doesn't know whether you intend that data to be a String
, or a ButtonField
, or a FuzzyWarble
. So, it has nothing more meaningful to print out than the object's address.
如果要打印出String
数据,则需要使用byte[]
创建一个String
对象,但是要这样做,您需要使用默认的和"ASCII"
是两种流行的编码.
If you want to print out String
data, you need to create a String
object with the byte[]
, but to do that, you need to either use the default character encoding, or specify which encoding you want. "UTF-8"
and "ASCII"
are two popular encodings.
如果我运行这段代码
try {
byte[] bytes = new byte[] { 100, 67, 126, 35, 53, 42, 56, 126, 122 };
System.out.println("bytes are " + bytes.toString());
String s = new String(bytes, "UTF-8");
System.out.println("string is " + s);
} catch (UnsupportedEncodingException e1) {
}
我看到了
字节为[B @ 3b50e2ee
字符串是dC〜#5 * 8〜z
bytes are [B@3b50e2ee
string is dC~#5*8~z
如您所见,我看到的地址与您所看到的有所不同(因为我在不同的计算机上运行,并且具有不同的内存布局).但是,当用"UTF-8"
编码转换为String
时,我看到的是您看到的值.
As you see, the address I see is different from the one you see (because I'm running on a different machine, with different memory layout). But, when converted to a String
with "UTF-8"
encoding, I see the value that you see.
那么,也许这是正确的价值?
So, maybe that's the right value?
同样,我们不知道二进制数据来自何处,或者它应该是什么,但是我可以告诉你,上面的代码是将字节数组转换为字符串的典型方法.
Again, we don't know where the binary data comes from, or what it's supposed to be, but I can tell you that the code above is a typical way to convert byte arrays to strings.
这篇关于将字节数组转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!