0

I am trying to convert int into bits of specified length and storing them using StringBuilder. But my output is not the string of bits instead shows some random data. I took reference from this answer https://stackoverflow.com/a/27737240/10494810

 static StringBuilder final_string = new StringBuilder();
public static void main (String[] args) {
    int[] values = {2,4,7,8};
    int[] length = {8,10,10,7};
    appendString(values, '0', length);
}

public static void appendString(int[] in, char padChar, int[] length) {
    for(int j = 0; j< in.length;j++){
       String temp =Integer.toBinaryString(in[j]);
        int temp_length = length[j];
         StringBuilder sb = new StringBuilder(temp_length);
          sb.append(in);
            for (int i = temp.length(); i < temp_length; i++) {
             sb.insert(0, padChar);
             }
            final_string.append(sb);
   }
   System.out.println((final_string.toString()));

}

Output of the Above code is: 000000[I@232204a1[I@232204a1[I@232204a1[I@232204a1

Expected output is: 00000010 0000000100 0000000111 0001000

user207421
  • 305,947
  • 44
  • 307
  • 483
Xena_psk
  • 25
  • 8

1 Answers1

-1

Two errors:

1. sb.append(in);

You are appending the whole array, that means only the address (@xxxxxx) to the compiler. Did you mean sb.append(in[j]); ?

2. final_string.append(sb);

You can't append a StringBuilder to another the way you are assuming. This way you are actually using StringBuilder append(Object obj), so it only appends it as an object, again that means as an address or stuff like this. Consider using final_string.append(sb.toString()); or final_string.append(sb.substring(0)); instead.

Hope I helped

Sterconium
  • 559
  • 4
  • 20