Bob*_*bby 1 java arrays android
我试图使用整数数组将整数转换为二进制数.第一次转换是toBinaryString,我得到正确的转换"11111111"然后转换为数组的下一步.这是它出错的地方,我认为它是getChar线.
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]);
Run Code Online (Sandbox Code Playgroud)
日志显示(数据0,0,0)我要查找的结果是(数据1,1,1)
这是最终的代码,它的工作原理.
// 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]);
Run Code Online (Sandbox Code Playgroud)
// 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;
}
Run Code Online (Sandbox Code Playgroud)