假設10進位的數值為20那轉換為2進位的資料為10100,算法是如下:
20/2取餘數0,10/2取餘數為0,5/2取餘數為1,2/2取餘數為0,如此倒著排列為10100。
假設10進位的數值為20那轉換為16進位的資料為14,算法如下:
20/16取餘數4,如此倒著排列為14。
Xml的App中的Layout圖如下:
選擇Layout的物件請統一放置在Component Tree中,便可對所使用的物件做有效的應用。
下面的程式碼為參考網路上的相關資料撰寫而成的,而這部份只局限於JAVA中的MainActivity.java中。
package aixstudio.carryexample;
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity { /** Called when the activity is first created. */
int s,i,num,f; //宣告全域變數
int[] ba = new int[64]; //宣告全域變數
String [] da = new String[64]; //宣告全域變數
String su,sn; //宣告全域變數 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getSupportActionBar().setTitle("10進制轉2進制及16進制"); setContentView(R.layout.activity_main); final EditText editText1 = (EditText)findViewById(R.id.Et1); final TextView textView4 = (TextView)findViewById(R.id.Tv4 ); final TextView textView5 = (TextView)findViewById(R.id.Tv5 ); final Button button1= (Button)findViewById(R.id.Btn1); button1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { /* 這段程式碼為10進位轉換為2進位的程式碼*/
i = 0; su = "";
s = Integer.parseInt(editText1.getText().toString()); //輸入10進位的數值 while (s > 1) { ba[i] = s % 2; i++ ; s = s/2; } if(s==1 || s==0) ba[i] = s; for(int j=i;j>=0;j--) su += String.valueOf(ba[j]); textView4 .setText(su); /*********************************************************************/
/*這段程式為10進位轉成16進位*/
f = 0; sn = ""; //宣告變數f為0,sn為空字串
num = Integer.parseInt(editText1.getText().toString()); //輸入需轉換的數值 while ( num > 15 ) { int temp = num % 16; checkNum(temp); f++; num = num / 16; } checkNum(num); for ( int j = f; j >= 0; j-- ) sn += da[j]; textView5.setText(sn); } }); } //此函式檢查 10 ~ 15 所對應的 16 進位表示法
private void checkNum(int cn) { if ( cn > 9 ) { if (cn == 10) da[f] = "A"; else if (cn == 11) da[f] = "B"; else if (cn == 12) da[f] = "C"; else if (cn == 13) da[f] = "D"; else if (cn == 14) da[f] = "E"; else if (cn == 15) da[f] = "F"; } else da[f] = String.valueOf(cn); } }
下圖為使用模擬器所使用的結果。
沒有留言:
張貼留言