简体   繁体   English

将byte转换为int,反之亦然

[英]Convert byte to int and vice-versa

任何人都知道如何在java中将大量字节,前1000字节转换为int / long等?

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. 这样一个1000个元素可能需要10微秒。

To convert a byte to an int in Java, you have two options: 要在Java中将byte转换为int ,您有两个选择:

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. Java库中没有方法可以将数组从一种基本类型转换为另一种基本类型,您必须手动完成。

Thanks Paŭlo. 谢谢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));
    }

}

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

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