C
C
Chvalov2015-10-29 10:55:03
Java
Chvalov, 2015-10-29 10:55:03

How to correctly return values ​​back to bytes using bitwise operations?

There is a code with which I get normal values, in this case, currents
Need from an array of ints, back to an array of bytes

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        // Массив байт для обработки
        byte[] response = new byte[]{1, -92, 0, 0, 24, 1, 29, 1, -122, 1, -102, 1, -92, 1, 28, 2, 38, 2, 108, 2, 118, 2, -118, 2, -68, 2, -48, 2, 12, 3, 84, 3, 92, 3, -124, 3, 20, 5, 30, 5, 40, 5, 60, 5, 70, 5, 90, 5, 100, 5, 120, 5, -126, 5, 4, 6, 109, 6, -32, 6, 88, 7, -58, 7, -38, 7, 72, 8, -64, 8, 56, 9, -90, 9, 30, 10, 40, 10, 60, 10, 80, 10, 100, 10, -126, 10, -106, 10, -86, 10, 34, 11, -102, 11, 118, 12, -18, 12, 11, 13, 22, 13, 52, 13, 0, 68, 36};

        int FirstByteTmp, SecondByteTmp, ByteTmp;
        int MassCurrentsPhases[] = new int[50];
        // Цикл для подсчета и записи в массив обработаных данных
        for (int i = 0, j = 0; i < 50; i++, j += 2) {
            FirstByteTmp = (0x000000FF & ((int) response[5 + j]));
            SecondByteTmp = (0x000000FF & ((int) response[4 + j]));
            ByteTmp = (char) (FirstByteTmp << 8 | SecondByteTmp);
            MassCurrentsPhases[i] = (int) ByteTmp;
        }
        
        System.out.println("Длина" + response.length);
        System.out.println(Arrays.toString(MassCurrentsPhases));    // Выводим массив с данными
    }
}

At the output I have the following: Link
Question how do I get these values:
[280, 285, 390, 410, 420, 540, 550, 620, 630, 650, 700, 720, 780, 852, 860, 900, 1300, 1310, 1320, 1340, 1350, 1370, 1380, 1400, 1410, 1540, 1645, 1760, 1880, 1990, 2010, 2120, 2240, 2360, 2470, 2590, 2600, 2620, 2640, 2660, 2690, 2710, 2730, 2850, 2970, 3190, 3310, 3339, 3350, 3380]
Revert back to these bytes:
24, 1, 29, 1, -122, 1, -102, 1, -92, 1, 28, 2, 38, 2, 108, 2, 118, 2, -118, 2, -68, 2, -48, 2, 12, 3, 84, 3, 92, 3, -124, 3, 20, 5, 30, 5, 40, 5, 60, 5, 70, 5, 90, 5, 100, 5, 120, 5, -126, 5, 4, 6, 109, 6, -32, 6, 88, 7, -58, 7, -38, 7, 72, 8, -64, 8, 56, 9, -90, 9, 30, 10, 40, 10, 60, 10, 80, 10, 100, 10, -126, 10, -106, 10, -86, 10, 34, 11, -102, 11, 118, 12, -18, 12, 11, 13, 22, 13, 52, 13

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mercury13, 2015-10-29
@Chvalov

byte[] streamedResponse = new byte[100];
for (int iWord = 0, iByte = 4;
        iWord < 50;
        ++iWord, iByte += 2) {
    int w = MassCurrentsPhases[iWord];
    streamedResponse[iByte] = (byte)w;
    streamedResponse[iByte + 1] = (byte)(w >> 8);
}

What is the four-byte header you missed, I don't know.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question