java十进制转二进制,并且将01单独取出放到数组
(2)实现目的:
因为我们的机器返回的是二进制数据,在android端需要对这个二进制进行接收,但是这个二进制在接收的过程中被转换成了int数组接收显示的,所以需要我们另外写一个方法来进行还原
六种音源分别是
光纤,高电平,蓝牙,低电平,同轴,U盘播放器
对应的二进制分别为:
1 1 1 1 1 1 或者0 0 0 0 0 0
其中0表示没有此项音源,1表示有此音源,例如服务器返回给我们的int值是46,转换为2进制就是:101110
那么,我们的软件音源就包括U盘,低电平,蓝牙,高电平,光纤
如果服务器返回的数据是14,转换为二进制位001110.那么我们软件的音源为低电平、蓝牙、高电平
(3)实现代码:
public class MainActivity extends AppCompatActivity {
private TextView tv;
private EditText et;
private Button btn;
private final static int MAXbINARY = 6;
private String[] binaryTs = new String[MAXbINARY];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
tv = (TextView)findViewById(R.id.tv);
et = (EditText)findViewById(R.id.et);
btn = (Button)findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
@SuppressLint("SetTextI18n")
@Override
public void onClick(View view) {
try {
String a = et.getText().toString();
binaryToDecimal(Integer.parseInt(a));
}catch (Exception e){
e.printStackTrace();
}
}
});
}
public void binaryToDecimal(int n){
String str = "";
int i=0;
while(n!=0){
str = n%2+str;
Log.e("TAG","循环测试次数");
binaryTs[i] = String.valueOf(str.subSequence(0,1));
n = n/2;
i++;
}
System.out.println(str);
tv.setText(""+str);
for(int j=0;j<MAXbINARY;j++){
Log.e("TAG","打印数组: "+ binaryTs[j]);
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.administrator.testz.MainActivity">
<EditText
android:id="@+id/et"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:hint="请输入要转换的数字" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="十进制转二进制" />
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
end
上一篇:
IDEA上Java项目控制台中文乱码
