I'm trying to convert a byte array in string with simple code:
System.out.printf("%s \n", new String(b));
where b
has this content (in hex chars):
32d001000001000000000000246d3639653331697769736374683134633439687763796c7862796f74697167786f786c7504696e666f0000010001
If I run my code in Windows I get the entire decoded String
, however in Linux it seems dropped until the null byte (00). If I skip these bytes the correct String
in produced.
How can I get the same result in Linux OS? Sorry but I can't attach image due to restriction :'(
Thanks in advance!
Yes, that's because you're using the constructor that uses the platform default encoding to convert binary data to text. It's entirely reasonable for it to create different strings on different platforms - although I suspect your interpretation of Linux "dropping until the null byte" is incorrect, and may be due to the way you're displaying the strings.
Don't use the platform default encoding - or do so explicitly if you really want it. Assuming this really is text data, specify an appropriate encoding e.g. using StandardCharsets
.
However, if this is arbitrary binary data (e.g. the result of encryption or compression) then you shouldn't be converting it into a string in this way at all - you should use a hex or base64 conversion.
See more on this question at Stackoverflow