在不进行编码的情况下将字符串与字节数组相互转换 [英] Convert String to/from byte array without encoding

查看:83
本文介绍了在不进行编码的情况下将字符串与字节数组相互转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通过网络连接读取的字节数组,我需要将其转换为没有任何编码的String,即只需将每个字节视为字符的低端,而将高端保持为零即可。我还需要做相反的事情,我知道角色的高端将始终为零。

I have a byte array read over a network connection that I need to transform into a String without any encoding, that is, simply by treating each byte as the low end of a character and leaving the high end zero. I also need to do the converse where I know that the high end of the character will always be zero.

在网络上搜索会产生几个类似的问题,并且都得到了响应,表明必须更改原始数据源。

Searching the web yields several similar questions that have all got responses indicating that the original data source must be changed. This is not an option so please don't suggest it.

在C语言中这是微不足道的,但Java似乎要求我编写自己的转换例程,这很可能是可行的。效率很低。有没有一种我想念的简单方法?

This is trivial in C but Java appears to require me to write a conversion routine of my own that is likely to be very inefficient. Is there an easy way that I have missed?

推荐答案

下面是一个示例代码,它将转换 String byte数组并返回到 String 而不进行编码。

Here is a sample code which will convert String to byte array and back to String without encoding.

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

    }
}

这篇关于在不进行编码的情况下将字符串与字节数组相互转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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