我设置了一个数组[8]来存储字符串转换。 X的范围是0到255.如果X小于127(7位),它不会写高位0。所以我将数组[8]预设为全0,下一个例程只会写入已更改的数据。代码编译但是数组[]都读取1,无论x = to。
int x = 10;
string=(Integer.toBinaryString(x));
int[] array = new int[8];
for (int j=0; j < 7; j++){
array[j]=0;
}
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 :(得分:2)
int x = 10;
String s=(Integer.toBinaryString(x));
int[] array = new int[8];
//no need for a loop that sets all values to 0.
int offset = array.length - s.length();
//you need this offset because the string may be shorter than the array
for (int i=0; i < s.length(); i++) {
array[i + offset] = Integer.parseInt(s.substring(i,i+1));
//applay the offset here
}
这将生成int = 10
的跟随数组:
[0, 0, 0, 0, 1, 0, 1, 0]