简体   繁体   English

在java中将整数分解为个位数字节

[英]Break an integer to single digit bytes in java

I need to break a large integer into a single digit byte array.我需要将一个大整数分解为一个数字字节数组。 Like if the integer is 26051 , the byte array should be:就像整数是26051 ,字节数组应该是:

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

I've tried:我试过了:

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

But it is giving me errors as expected... Please suggest me a solution and sorry about my English.但它给了我预期的错误......请给我建议一个解决方案,并对我的英语感到抱歉。

You should spend more time on your question before posting it - if the code doesn't compile you should either mention that you have a problem compiling it, or you should fix it before posting.你应该在发布之前花更多的时间在你的问题上 - 如果代码不能编译,你应该提到你在编译它时遇到了问题,或者你应该在发布之前修复它。

But it's an interesting question nonetheless.但这仍然是一个有趣的问题。 You can do this:你可以这样做:

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);
    }
}

I hope this might help you.我希望这可以帮助你。

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);
    }
}
 byte b[]  = new byte[20]; 

应该有效..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM