我正在尝试使用整数数组将整数转换为二进制数。第一次转换是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]);
日志显示(数据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]);
答案 0 :(得分:5)
// 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;
}
答案 1 :(得分:2)
首先,数组从索引0开始而不是1,因此更改以下代码行:
Log.d("TAG", " Data " + array[1] "," + array[2] + "," + array[3]);
要:
Log.d("TAG", " Data " + array[0] "," + array[1] + "," + array[2]);
接下来,以下代码行:
array[i] = string.getChar(i);
您正在尝试获取Integer数组的字符值,您可能需要尝试以下操作并将值解析为Integer(同样,“getChar”函数不存在):
array[i] = Integer.parseInt(String.valueOf(string.charAt(i)));
我希望我能帮到你。
P.S - 感谢Hyrum Hammon指出String.valueOf。
答案 2 :(得分:2)
怎么样:
array[i] = Integer.parseInt(string.substring(i,i+1));