【发布时间】:2013-04-20 14:40:24
【问题描述】:
我在 java 中有一个名为 byteval 的 byte[] 数组,如果我执行 System.out.println(byteval),我可以读取:d3e1547c254ff7cec8dbcef2262b5cf10ec079c7[B@40d150e0
现在我需要这个我在那里读到的字符串,但是如果我尝试用 Byte.toString 或新的字符串构造函数转换它,值就不一样了,大多数都是一些数字。
那么我怎样才能将 byte[] 数组作为一个名为 strval 的字符串,同时切断 [B@40d150e0?
现在:System.out.println(byteval)>> d3e1547c254ff7cec8dbcef2262b5cf10ec079c7[B@40d150e0
目标:System.out.println(strval)>> d3e1547c254ff7cec8dbcef2262b5cf10ec079c7
非常感谢! 丹尼
编辑:适合我的解决方案:
byte[] byteval = getValue();
// Here System.out.println(byteval) is
// d3e1547c254ff7cec8dbcef2262b5cf10ec079c7[B@40d150e0
BigInteger bi = new BigInteger(1, byteval);
String strval = bi.toString(16);
if ((strval.length() % 2) != 0) {
strval = "0" + strval;
}
System.out.println(strval);
// Here the String output is
// d3e1547c254ff7cec8dbcef2262b5cf10ec079c7
感谢所有回答者。
【问题讨论】:
-
我假设您使用的是
System.out.println(array[0]);而不仅仅是试图输出数组 -
不,D 先生,我对孔阵列进行 sysout,而不仅仅是一个索引。这向我展示了价值,我需要什么,但我无法将其作为字符串获取。
-
和
array[0] == d3e1547c254ff7cec8dbcef2262b5cf10ec079c7的值? -
System.out.println(byteval)打印出[B@40d150e0。d3e1547c254ff7cec8dbcef2262b5cf10ec079c7必须打印在其他地方。删除System.out.println(byteval)看看发生了什么。 -
D 先生,在数组 [0] 中为 d3e1547c254ff7cec8dbcef2262b5cf10ec079c7-45。但这对我没有多大帮助,因为它甚至是一个字节,我需要它在一个字符串 var 中。如何在字符串中获取数组 [0]? String strval = array[0].toString() 不可用并且 String.ValueOf(array[0]) 和 new String(array[0], 'UTF-8') 不可用