简体   繁体   English

从字节数组到字符串的数据转换

[英]Data conversion from byte array to String

I'm trying to convert Byte Array to String with Following code snippet. 我正在尝试使用以下代码片段将字节数组转换为字符串。 But for some reasons, when i convert the byte[] to string, it changes the some content in in file 但是由于某些原因,当我将byte []转换为字符串时,它将更改文件中的某些内容

Code

public String convertToString(byte[] byteArr)
  {
    public static final int BYTE_MASK = 0xFF;
    StringBuilder strBldr = new StringBuilder();

    for(int i = 0; i < byteArr.length; i++ ) {
      strBldr.append((char) (byteArr[i] & BYTE_MASK));
    }

    return strBldr.toString();
  }

I have added the data of two files called expected file and generated file 我添加了两个文件的数据,分别是期望文件和生成文件

Expected File: 预期文件:

00 39 00 00 46 91 00 00 00 17 16 02 16 16 39 31
0b 00 3a 00 78 09 60 40 26 64 50 41 50 20 48 49
47 20 52 4d 20 20 04 00 80 4b 02 00 a0 ea 01 00
64 00 ec 05 00 00 00 00 00

Generated File: 生成的文件:

00 39 00 00 46 3f 00 00 00 17 16 02 16 16 39 31
0b 00 3a 00 78 09 60 40 26 64 50 41 50 20 48 49
47 20 52 4d 20 20 04 00 3f 4b 02 00 a0 ea 01 00
64 00 ec 05 00 00 00 00 00

if you see both files, then expected file data should be "91"(First row,sixth element) and its 3f in generated file. 如果同时看到两个文件,则预期的文件数据应为“ 91”(第一行,第六个元素)及其在生成文件中的3f。

Any idea how would get a correct output? 知道如何获得正确的输出吗?

try this: 尝试这个:

        String example = "This is an example";
        byte[] bytes = example.getBytes();
        System.out.println("Text : " + example);

        String s = new String(bytes);
        System.out.println("String : " + s);

output: 输出:

Text : [B@187aeca 文字:[B @ 187aeca

String : This is an example 字符串:这是一个示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM