Danadir
Danadir

Reputation: 11

Convert byte to int and vice-versa

Anyone know how can I convert a large array of bytes, ex 1000 bytes into an int/long etc in java?

Upvotes: 1

Views: 1715

Answers (3)

shams
shams

Reputation: 3508

Thanks Paŭlo. Here's the corrected answer:

public class Main {

    public static int[] convert(byte[] in) {
        int bytesPerSample = 4;
        int[] res = new int[in.length / bytesPerSample];

        for (int i = 0; i < res.length; i++) {
            int bOffset = i * bytesPerSample;
            int intVal = 0;
            for (int b = 0; b < bytesPerSample; b++) {
                int v = in[bOffset + b];
                if (b < bytesPerSample - 1) {
                    v &= 0xFF;
                }
                intVal += v << (b * 8);
            }
            res[i] = intVal;
        }

        return res;
    }

    public static byte[] convert(int[] in) {
        int bytesPerSample = 4;
        byte[] res = new byte[bytesPerSample * in.length];

        for (int i = 0; i < in.length; i++) {
            int bOffset = i * bytesPerSample;
            int intVal = in[i];
            for (int b = 0; b < bytesPerSample; b++) {
                res[bOffset + b] = (byte) (intVal & 0xFF);
                intVal >>= 8;
            }
        }

        return res;
    }

    public static void main(String[] args) {
        int[] in = {33, 1035, 8474};
        byte[] b = convert(in);
        int[] in2 = convert(b);
        System.out.println(Arrays.toString(in2));
    }

}

Upvotes: 0

Aaron Digulla
Aaron Digulla

Reputation: 328574

To convert a byte to an int in Java, you have two options:

byte val = 0xff;
int a = val;          // a == -1
int b = (val & 0xff); // b == 0xff

There is no method in the Java library to convert an array from one primitive type to another, you'll have to do it manually.

Upvotes: 2

Peter Lawrey
Peter Lawrey

Reputation: 533492

You can use a loop

byte[] bytes =
int[] ints = new int[bytes.length];
for(int i=0;i<bytes.length;i++)
   ints[i] = bytes[i];

A 1000 elements might take up to 10 micro-seconds this way.

Upvotes: 2

Related Questions