如果我有一個二進制符號,例如「1000010」,它等於66,我想將它增加一個「1000011」,它等於67.在我的數組中,這樣做是否正確?目前它打印出「0100010」,即34,但沒有接近正確的答案。我不認爲我的陣列正在正確移動,也不會隨着數字變大而增加大小。儘管如此,除了明確指出的內容外,我無法對數組的大小做出任何假設。如何正確增加數組中的位?
public class math {
//=================================================================
// increment(A) returns an array of bits representing A+1.
//=================================================================
public static byte[] increment(byte[] A)
{
byte carry= 1;
for(int i = 0; i<A.length; i++){
byte b = A[i];
A [i] ^= carry;
carry &= b;
}
return A;
}
private static String toBinString (byte [] a)
{
String res = "";
for (int i = 0; i <a. length; i++)
{
res = (a [i] == 0 ? "0": "1") + res;
}
return res;
}
/**
* @param args
*/
public static void main(String[] args) {
byte [] A ={1,0,0,0,0,1,0};
increment(A);
System.out.println (toBinString (A));
}
}
相關:http://stackoverflow.com/questions/1034473/java-iterate-bits- in-byte-array – 2011-09-07 00:25:05
在聲明A時,它看起來像是最左邊的(第一個)數組是最重要的位,在程序的其餘部分中,您認爲數組的第一個元素是最不重要的位。最簡單的解決方案可能是以相反的順序在數組中輸入數字,或者反轉數組... – fvu
此解決方案適用於我:https://stackoverflow.com/questions/4421400/how-to-get-0- padded-binary-representation-of-an-in-java – HoldOffHunger