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 know symptomsBit.split(" ") isn't correct. But do not know how to further improve it.
Yes, you're almost there but must have made a few minor mistakes.
For one, that split()
isn't correct because you're trying to split it on " "
s but what you need is ""
s because it's a continuous string.
That will give you the array that you think you're getting. But you also don't print the elements right. You should index into the array to get the element to print. Like so...
int 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]);
}