如何从 Java 中的字节数组中删除前 4 个字节?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26923408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 10:52:52  来源:igfitidea点击:

How to remove first 4 bytes from a byte array in Java?

javaarraysbytearraydatainputstream

提问by Miller

I have a byte array named byteArr[].I need to remove first 4 bytes from it.My code is shown below. Here I use the byte array to store the input string.I got some unwanted byte with the output i.e the first four bytes is not needed from the fifth onwards is correct. My program is to take id from respected rfid tag using an rfid machine.

我有一个名为byteArr[].I的字节数组。我需要从中删除前 4 个字节。我的代码如下所示。这里我使用字节数组来存储输入字符串。我在输出中得到了一些不需要的字节,即从第五个开始不需要前四个字节是正确的。我的程序是使用 rfid 机器从受人尊敬的 rfid 标签中获取 id。

public class Serverc {

    final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();

    public static String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];

        for (int j = 0; j < bytes.length; j++) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }

    public static void connection() throws IOException {

        ServerSocket ss = new ServerSocket(9888);//exce
        ss.setSoTimeout(300000000);//exce
        System.out.println("Waiting for client on port " + ss.getLocalPort() + "...");

        while (true) {

            Socket server = ss.accept();//exce
            System.out.println("Just connected to " + server.getRemoteSocketAddress());

            int available = 0;
            DataInputStream in = new DataInputStream(server.getInputStream());//exce
            int input = 0;
            //BufferedReader br = new BufferedReader(in);
            byte byteArr[] = new byte[28];

            try {
                //read till the end of stream
                //while((input = in.available()) != -1)
                while ((input = in.read(byteArr)) != -1) {
                    System.out.println("Size read is " + input);
                    System.out.println("Data is " + bytesToHex(byteArr));
                }

                //System.out.println("inside finally");
                server.close();//exce
                //System.out.println("outside finally");
            } catch (SocketTimeoutException ex) {
                System.out.println("Socket timed out!");
            }

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {

                e.printStackTrace();
            }
        }
    }

    public static void main(String args[]) throws IOException {
        Serverc obj = new Serverc();
        obj.connection();
    }
}

Here is my console

这是我的控制台

Waiting for client on port 9888...
Just connected to /106.208.71.50:61532
Size read is 28
Data is 55000016910001DB00FB63ABEEAFC1EC888F10263410050711148F3500000000
Size read is 28
Data is 55000016910001DB00FB63ABEEAFC1EC888F10263410050711148F3500000000
Size read is 28
Data is 55000016910001DB00FB63ABEEAFC1EC888F10263410050711148F3500000000
Size read is 28
Data is 55000016910001DB00FB63ABEEAFC1EC888F10263410050711148F3500000000
Size read is 28
Data is 55000016910001DB00FB63ABEEAFC1EC888F10263410050711148F3500000000

Here I need to remove 55000016 from the output. Advance thanks

在这里,我需要从输出中删除 55000016。提前致谢

采纳答案by Elliott Frisch

If you want to skip the first four bytes change this,

如果你想跳过前四个字节改变这个,

for (int j = 0; j < bytes.length; j++) {

to something like

for (int j = 4; j < bytes.length; j++) {

Or you might use String.substring(int)

或者你可以使用 String.substring(int)

 bytesToHex(byteArr).substring(8); // <-- skip the first 4 bytes

回答by Pasang Sherpa

You could use Arrays.copyOfRange method to filter the unwanted bytes and save the result to a new byte array.

您可以使用 Arrays.copyOfRange 方法来过滤不需要的字节并将结果保存到新的字节数组中。

byte[] filteredByteArray = Arrays.copyOfRange(byteArr, 4, byteArr.length - 4);

回答by marcelv3612

It is best for you to skip the 4 bytes. But if you want to remove them, you should use this solution (your array may become massive). This algorithm is best you can get in Java for your problem. O(1) space , O(n) time.

最好跳过这 4 个字节。但是如果你想删除它们,你应该使用这个解决方案(你的阵列可能会变得很大)。这个算法最适合你在 Java 中得到的解决你的问题。O(1) 空间,O(n) 时间。

void removeFourBytes(byte[] a) {
  for (int i = 4; i < a.length; i++) {
    a[i-4]=a[i];
  }
  for (int i = a.length - 1; i > a.length - 5; i--) {
    a[i] = 0;
  }
}

Second best option would be System.arrayCopy() - O(n) space, O(n) time.

第二个最佳选择是 System.arrayCopy() - O(n) 空间,O(n) 时间。

回答by Jules

You have a larger problem than skipping the 4 bytes at the start of each of your packets. Your code does this:

您有一个比在每个数据包开始时跳过 4 个字节更大的问题。您的代码执行以下操作:

       byte byteArr[] = new byte[28];

        try {
            while ((input = in.read(byteArr)) != -1) {
                System.out.println("Size read is " + input);
                System.out.println("Data is " + bytesToHex(byteArr));
            }

(commented-out lines removed)

(已删除注释行)

Note that you cannot guarantee that all 28 bytes will be read on each call to in.read(), but that your bytesToHex()method is assuming that 28 valid bytes are present in the array. You need to collect data that you read into the array until you have all of your packet before processing it, probably using a DataInputStreamwith the method readFully(byte[]). Thenyou can skip the first 4 bytes as suggested in the other answers.

请注意,您不能保证每次调用 时都会读取所有 28 个字节in.read(),但您的bytesToHex()方法假设数组中存在 28 个有效字节。在处理数据包之前,您需要收集读入数组的数据,直到获得所有数据包,可能使用DataInputStream方法readFully(byte[])然后您可以按照其他答案中的建议跳过前 4 个字节。