我有一个通过网络连接读取的字节数组,我需要将其转换为没有任何编码的字符串,即简单地通过将每个字节视为字符的低端并将高端零保留为零。我还需要做相反的事情,我知道角色的高端将始终为零。
搜索网络会产生几个类似的问题,所有问题都得到答复,表明必须更改原始数据源。这不是一个选择,所以请不要建议。
这在C语言中是微不足道的,但是Java似乎要求我编写自己的转换例程,该转换例程可能效率很低。我错过了一个简单的方法吗?
下面是一个示例代码,将其转换String
到byte array
和回String
没有编码。
public class Test
{
public static void main(String[] args)
{
Test t = new Test();
t.Test();
}
public void Test()
{
String input = "Hèllo world";
byte[] inputBytes = GetBytes(input);
String output = GetString(inputBytes);
System.out.println(output);
}
public byte[] GetBytes(String str)
{
char[] chars = str.toCharArray();
byte[] bytes = new byte[chars.length * 2];
for (int i = 0; i < chars.length; i++)
{
bytes[i * 2] = (byte) (chars[i] >> 8);
bytes[i * 2 + 1] = (byte) chars[i];
}
return bytes;
}
public String GetString(byte[] bytes)
{
char[] chars = new char[bytes.length / 2];
char[] chars2 = new char[bytes.length / 2];
for (int i = 0; i < chars2.length; i++)
chars2[i] = (char) ((bytes[i * 2] << 8) + (bytes[i * 2 + 1] & 0xFF));
return new String(chars2);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句