我在byte[]数组中存放了一些二进制的数字,例如{ (byte)0xeb, (byte)0x10, (byte)0x5b等,然后把它转换到String里去,作为一个参数传递给一个函数,请问如何转换才不会让这些二进制的数字被改变呢?(貌似在转换时要经过编码,所以会改变0xeb等值)

解决方案 »

  1.   

    String str = new String(byte);
    就可以了.
      

  2.   

                tempa = Integer.toHexString(((int) byte[i]) & 0xff);
                if (tempa.length() < 2) {
                    tempa = '0' + tempa;
                }
      

  3.   

    String now = new String(byte[]);
      

  4.   

    byte[] 
    recdata = new byte[len];
    String hex = "";
    for (int i = 0; i < recdata.length; i++) {
    recdata[i] = dis.readByte();
    hex += Integer.toHexString(recdata[i] & 0xFF);
    if (hex.length() == 0) {
    hex = '0' + hex;
    }
    }
      

  5.   

    支持楼上的,
    String str = new String(byte[]);就可以了啊
      

  6.   

    是会变的!~
    lz为什么要转换成string在传给函数,不直接传byte[]!
      

  7.   

    String str = new String(byte[])会变的,我之所以不用byte[]直接传是因为用的别人的接口,只能是String类型的
      

  8.   

    谢谢你回帖子,但是Integer.toHexString()这个函数返回的是数字所对应的十六进制形式的字符传,我想要的是:让字节丝毫不变的放在String里,例如C++中,可以有这样的字符串“\xeb\x10\5b",在Java的String里如何做到?或者说实现同样的效果
      

  9.   

    String now = new String(byte[]);
      

  10.   

    答:楼主说得对。String str = new String(byte[])会变的(经过charset编码处理,处理的代码是这一句:char[] v = StringCoding.decode(charsetName, bytes, offset, length);
    )。
    因此,必须直接将两个字节硬拼装成一个Char(不经过charset编码处理)。这正是DataInputStream的readChar()特性.代码如下://说明:利用DataInputStream的readChar()特性:
    //设 a 为第一个读取字节,b 为第二个读取字节。返回的值是:
    //(char)((a << 8) | (b & 0xff)) public static String byteToString(byte[] bytes) throws IOException
    {
    CharArrayWriter caw = new CharArrayWriter();
    DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bytes));
    try{
    char c=0;
    while(true)
    {
    c=dis.readChar();
    caw.append(c);
    }
    }catch(EOFException e){}
    return caw.toString();//直接将字符数组强行将成String。
    }
    以上仅供你参考
      

  11.   

    答:更好的办法是:保持字节值不变的情况下,将一个字节扩展成一个字符。对方读到的每一个字节,值就是原来的字节值。public static String byteToString(byte[] bytes) throws IOException
    {
    CharArrayWriter caw = new CharArrayWriter();
    for(byte e:bytes)
    {
    caw.append((char)(e&0x000000ff));
    }
    caw.flush();
    return caw.toString();
    }
      

  12.   

    答:或者把CharArrayWriter改为StringBuilder更好。
    以上仅供你参考
      

  13.   

    byte b[] = new byte[];
    StringBuffer message = new StringBuffer();
    char c ;
    for(int i=0;i<b.length;i++{
        c = (char)b[i];
        message.append(c);
    }
    System.out.println(message.toString());