2

I have a byte array which contains text padded with values 0 up to fill 16 bytes.

When I try to convert it to String I can not get the right length/String, it always retrieves the whole 16 characters.

I have tried:

import java.nio.charset.StandardCharsets;

public class HelloWorld{

     public static void main(String []args){

        // SIMULATED BYTE[] CONTAINS "ABC" PLUS CHAR(0) UNTIL FILL 16 BYTES
        byte[] name = new byte[16]; 
        for(int i=0; i<16; i++) {
            name[i] = 0;
        }
        name[0] = 'A';
        name[1] = 'B';
        name[2] = 'C';

        // DESIRED OUTPUT IS A STRING = "ABC".
        // I.E. REMOVAL OF PADDING WITH CHAR(0)s
        String nameStr = new String(name, StandardCharsets.US_ASCII);

        System.out.println("#"+nameStr+"#");
        System.out.println(nameStr.length());

     }
}

This is the output:

output

The desired retrieved length is 3, not 16. Also it can be seen in NetBeans output how the String contains the padding 0 values.

I am using OpenJDK8 under FreeBSD and NetBeans 11.

6
  • Why not use replaceAll? Also, I think the for-loop is unnecessary, since the byte array will initially contain zeroes anyways Commented May 19, 2020 at 15:12
  • The byte[] is read from a file, this is a simplified example to allow posting a replicable example. What I intend to do is to read a variable string (up to 16 chars) but I am reading always 16 chars, even the '0' values stored in the unused byte[] positions. Commented May 19, 2020 at 15:14
  • 1
    This looks like XY problem. Why do you build string via byte array in the first place? Commented May 19, 2020 at 15:14
  • 1
    related stackoverflow.com/questions/17003164/… Commented May 19, 2020 at 15:15
  • If you are reading text from file then don't read it as bytes. Use proper Reader or Scanner to handle converting bytes to chars for you. Commented May 19, 2020 at 15:15

3 Answers 3

5

The straight-forward approach is to identify the trailing zeros and specify a range to the String constructor:

int end = name.length;
while(end > 0 && name[end - 1] == 0) end--;
String nameStr = new String(name, 0, end, StandardCharsets.US_ASCII);
Sign up to request clarification or add additional context in comments.

4 Comments

bye Algorithmic approach it is correct.
try theses name[1] = 'A'; name[2] = 'B'; name[9] = 'C';
@sc0der there is no requirement to remove zero bytes at the beginning, in fact, it’s contradicting the OP’s intention. They are obviously parsing a file format which has zero byte padding at the end of a fixed size field. That’s not an unusual requirement.
I have marked as solution the one that suggests using trim. However this one could be perfectly a valid solution. And I guess that if you have to repeat this operation many times it makes much more sense to use this one. I just feel that for my specific case trim is easier to read and use.
1

You can trim the string

String nameStr = new String(name, StandardCharsets.US_ASCII).trim();

System.out.println("#" + nameStr + "#");
System.out.println(nameStr.length());

Output

#ABC#
3

2 Comments

This removes more than just zero padding bytes, i.e. it also removes space characters at the beginning.
This option is probably the simplest. As the operation takes place just once at the beginning of the reading I do not care if this is more expensive computationally than the one that suggest to identify the 0s and later specify the length in the string constructor. In my specific case there are no spaces at all.
1

replaceall

Update the string and remove unwanted characters

String nameStr = new String(name, StandardCharsets.US_ASCII).replaceAll("\0", "");

, output

#ABC#

3 Comments

note - this will not work if somehow there are symbols after first 0 in array, which is probably not a big deal for this particular question
@IłyaBursov it’s also a heavy operation, considering that it will use the regex pattern matching engine behind the scenes.
I think regex might be overkilling for my specific case, it is easier to use trim as suggested below. It is good to know anyway.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.