2014-04-05 55 views
-2

我需要將大整數分解爲單個數字字節數組。如果該整數26051一樣,字節數組應該是:在java中將整數分解爲單個數字字節

b[0]=2, b[1]=6, b[2]=0, b[3]=5, b[4]=1. 

我已經試過:

int i,j=0; 
    byte b[] = new byte[20]; 
    //read integer i 
    while(i>0) 
     { b[j]=i%10; 
     i=i/10; 
     j++ 
     } 

但它給我的錯誤預期... 請建議我一個解決方案,對不起我的英語。

+3

你還沒有初始化'b'。 –

+0

當你開始while循環時,'i'應該開始於什麼時候? '20'? –

+1

你的代碼是無效的Java代碼(它不會編譯)。 –

回答

0
byte b[] = new byte[20]; 

應該是有效的..

1

我希望這可以幫助你。

private static void breakDigits(int i) { 
    List<Integer> digits = new ArrayList<Integer>(); 
    while(i>0){ 
     Integer next = i % 10; 
     i = i/10; 
     digits.add(0,next); 
    } 

    for(Integer element:digits){ 
     System.out.print(element); 
    } 
} 
2

你應該把錢花在你的問題更多的時間發佈之前 - 如果代碼不編譯您應該提到的是你有編譯它有問題,或發佈之前,你應該修復它。

但這仍是一個有趣的問題。你可以這樣做:

public static void main(String[] args) { 
    // 'i' is the number to process - left code similar to the question 
    int i = 26051, j = 0; 
    // Allocate as many bytes as needed. The 10-log of the number, 
    // rounded up, is the number of digits in the decimal representation. 
    byte[] b = new byte[(int) Math.ceil(Math.log10(i))]; 
    while (i > 0) { 
     // Work backwards through the byte array so that the most significant 
     // digit ends up first. 
     b[b.length - 1 - j] = (byte) (i % 10); 
     i = i/10; 
     j++; 
    } 

    // Print the result 
    for (byte x : b) { 
     System.out.println(x); 
    } 
} 
+0

我承認你的解決方案比我的更好。 +1 – Ashish

+0

結果是一樣的:-)你也可以使用'digits.add(0,next)'以正確的順序得到列表而不用'reverse'調用。 –

+0

謝謝修改代碼。 – Ashish

相關問題