0

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

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.

Any idea how would get a correct output?

user3257435
  • 103
  • 2
  • 10
  • 2
    tried: new String(byteArr); ? – Stultuske Feb 16 '16 at 11:52
  • 1
    How are you converting the bytes back to a byte[] ? – Ferrybig Feb 16 '16 at 11:52
  • Possible duplicate of [Java Byte Array to String to Byte Array](http://stackoverflow.com/questions/6684665/java-byte-array-to-string-to-byte-array) – SomeJavaGuy Feb 16 '16 at 11:52
  • 2
    Is this really text data? Otherwise you should not try to stick it into a String. And if it is, you need to make sure the encoding is correct (and I am not sure that there is one that matches your current method of conversion). – Thilo Feb 16 '16 at 11:59

1 Answers1

0

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

String : This is an example

tabby
  • 1,878
  • 1
  • 21
  • 39