I am trying to convert an integer to a binary number using an integer array. The first conversion is toBinaryString where I get the proper conversion "11111111" then the next step to convert to an array. This is where it goes wrong and I think its the getChar line.
int x = 255;
string=(Integer.toBinaryString(x));
int[] array = new int[string.length()];
for (int i=0; i< string.length(); i++){
array[i] = string.getChar(i);
Log.d("TAG", " Data " + array[1] "," + array[2] + "," + array[3]);
Log displays ( Data 0,0,0 ) the results I am looking for is ( Data 1,1,1 )
Here is the final code and it works.
// NEW
int x = 128;
string=(Integer.toBinaryString(x));
int[] array = new int[string.length()];
for (int i=0; i < string.length(); i++) {
array[i] = Integer.parseInt(string.substring(i,i+1));
}
Log.d("TAG", "Data " + array[0] + "" + array[1]+ "" + array[2] + "" + array[3]+ " " + array[4]+ "" + array[5] + "" + array[6] + "" + array[7]);
// Take your input integer
int x = 255;
// make an array of integers the size of Integers (in bits)
int[] digits = new Integer[Integer.SIZE];
// Iterate SIZE times through that array
for (int j = 0; j < Integer.SIZE; ++j) {
// mask of the lowest bit and assign it to the next-to-last
// Don't forget to subtract one to get indicies 0..(SIZE-1)
digits[Integer.SIZE-j-1] = x & 0x1;
// Shift off that bit moving the next bit into place
x >>= 1;
}
First of all, an array starts from the index of 0 instead of 1, so change the following line of code:
Log.d("TAG", " Data " + array[1] "," + array[2] + "," + array[3]);
To:
Log.d("TAG", " Data " + array[0] "," + array[1] + "," + array[2]);
Next, the following line of code:
array[i] = string.getChar(i);
You are trying to get a character value to an Integer array, you may want to try the following instead and parse the value into an Integer (also, the "getChar" function does not exist):
array[i] = Integer.parseInt(String.valueOf(string.charAt(i)));
I hope I've helped.
PS - Thanks to Hyrum Hammon for pointing out about the String.valueOf.
怎么样 :
array[i] = Integer.parseInt(string.substring(i,i+1));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.