简体   繁体   中英

Converting char array to int array without a loop in Java?

I need to get the binary representation for a range of numbers inside a matrix in order to perform some operations with another vector.

So let's say I will get the binary representation for 2^4 numbers, that's it from 0 to 15. I know I need a 16x4 matrix.

I've got this code:

int [][] a = new int[15][4];

for (int i = 0; i < a.length; i++) {
    a[i] = String.format("%5s", Integer.toBinaryString(i)).replace(' ', '0').toCharArray();
}

So, being the array representation of the binary formatted number a char[] , I can't just asign it to a[i] .

If there any way to perform a cast without looping through the char array?

Not that I am aware of. There are some different ways you can do it, either looping through the integer representation of the binary string, and the taking num%10 and num/10 for every step, if you absolutely don't want a loop through the char array. However in this case it seems pretty straight forward to just loop through the char array. Anyways here is the solution, in the way you didn't want it I guess...

int [][] a = new int[16][4];

for (int i = 0; i < a.length; i++) {
    char[] cArr = String.format("%4s", Integer.toBinaryString(i)).replace(' ', '0').toCharArray();
    for(int j = 0; j < a[0].length; j++)
        a[i][j] = Integer.parseInt(cArr[j]+"");

}

This is a simpler solution to what you are trying to accomplish...

    for (int i = 0; i < a.length; i++) {
        for (int j = 0; j < a[0].length; j++) {
            a[i][a[0].length - 1 - j] = (i & (1 << j)) != 0 ? 1 : 0;
        }
    }

Instead of converting an integer i to String and then replacing white spaces with zeros and then converting it to array, you:

  1. Take i.

  2. Take a binary number A with the only 1 at j-th position (other being zeros): A = (1 << j)

  3. Perform conjunction (binary bit-wise multiplication) of your number and the number A. This is accomplished by: (i & A)

  4. If there was non-zero bit at that position, after conjunction you will get A. If there was a zero bit, you will get 0.

  5. If the result is not zero, i has non-zero bit in j-th position. Otherwise it has zero there.

The solution using bit-wise operations will be faster too.

I believe that one outer loop will still be required to iterate through char[][] rows .

int[] charArray2intArray(char[][] binary) {

    int[] numbers = new int[binary.length];
    int row = 0;
    for (char[] number: binary) {

        String bin = new String(number);
        numbers[row++] = Integer.parseInt(bin, 2);
    }

    return numbers;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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