Say I have an Integer, I convert it to binary string first.
int symptomsM = 867;
String symptomsBit = Integer.toBinaryString(symptomsM);
In this case, I would have symptomsBit as 1101100011 in binary.
But how can I further convert it to Int Array that has the same content, such as
symptomsBitArr[] = {1,1,0,1,1,0,0,0,1,1}?
Okay. Here is what I have tried. I know symptomsBit.split(" ") isn't correct. But do not know how to further improve it.
symptomsM = 867;
String symptomsBit = Integer.toBinaryString(symptomsM);
String[] symptomsBitArr = symptomsBit.split(" ");
System.out.println("symptomsBit: " + symptomsBit);
System.out.println("symptomsBitArray: " + symptomsBitArr);
int[] symptomsArray = new int[symptomsBitArr.length];
for (int i = 0; i < symptomsBitArr.length; i++) {
symptomsArray[i] = Integer.parseInt(symptomsBitArr[i]);
System.out.println("symptomsArray: " + symptomsArray);
}
I tried the way Idos suggested as below:
symptomsM = 867;
String symptomsBit = Integer.toBinaryString(symptomsM);
String[] symptomsBitArr = symptomsBit.split(" ");
System.out.println("symptomsBit: " + symptomsBit);
System.out.println("symptomsBitArray: " + symptomsBitArr);
int[] symptomsArray = new int[symptomsBitArr.length];
for (int i = 0; i < symptomsBitArr.length; i++) {
//symptomsArray[i] = Integer.parseInt(symptomsBitArr[i]);
symptomsArray[i] = Integer.parseInt(String.valueOf(symptomsBit.charAt(i)));
System.out.println("symptomsArray: " + symptomsArray);
}
But it still not works. Here is the output:
symptomsBitArray: [Ljava.lang.String; @2a139a55
symptomsArray: [I@15db9742
I think this should do the trick:
String symptomBit = "1010";
for(int i = 0; i < symptomsBitArr.length; i++) {
symptomsBitArr[i] = Integer.parseInt(String.valueOf(symptomsBit.charAt(i)));
}
// symptomsBitArr = [1,0,1,0]
// print array here
for (int j = 0; j < symptomsBitArr.length; j++) {
System.out.println("symptomsArray: " + symptomsArray[j]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With