[英]Problems with Binary to Decimal conversion in java (arrays)
我的任務是在不使用預先編寫的方法(沒有用戶輸入)的情況下將 JLabel 數組中的二進制轉換為十進制。 我有正確的想法,但由於某種原因,輸出總是有點偏離。 我已經經歷了無數次,但我找不到我的算法有什么問題,我很困惑為什么它沒有產生正確的答案。 如果有人可以幫助我,我將不勝感激。 謝謝!
旁注:我已經閱讀了有關二進制到十進制轉換的類似討論線程,但我不明白如何使用數組進行轉換。
這是我的代碼片段:
private void convert()
{
int[] digit = new int[8]; //temporary storage array
int count = 0;
for(int x = 0; x < digit.length; x++)
{
digit[x] = Integer.parseInt(bits[x].getText()); //bits is the original array
count= count + digit[digit.length - 1 - x] * (int)(Math.pow(2, x));
}
label.setText("" + count);
}
您從左到右跟蹤二進制數,但抓取了錯誤的數字。 您想要相同的數字,但要乘以 2 的右冪 - 第一個索引是 +n*128 而不是 +n*1
int count = 0;
for(int i = 0; i < bits.length; i++) {
count += Integer.parseInt(bits[i].getText()) * Math.pow(2, bits.length - i - 1);
}
顯然,您的代碼段中存在錯誤。
您設置了數字 [x],但未設置數字 [長度 - 1 - x]。
例如,x = 0,您設置了 digit[0],但未設置 digit[7]。
因此,當您要在此處使用 digit[length - 1 -x] 時會出現錯誤:
count= count + digit[digit.length - 1 - x] * (int)(Math.pow(2, x));
這是這里的正確代碼:
private void convert()
{
int count = 0, length = 8;
for(int i = 0; i < length; count += Integer.parseInt(bits[i].getText()) * (1 << (length - 1 - i)), i++);
label.setText("" + count);
}
沒有測試代碼。 但我認為它會起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.