C
C
Chvalov2015-09-09 10:37:09
Java
Chvalov, 2015-09-09 10:37:09

How to decompose a number back into bytes (bitwise operations) in Java?

Here is the code:

import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        byte[] bytes = new byte[]{1, -96, 0, 0, -56, 0, 40, 0, -56, 0, -56, 0, -56, 0, -56, 0, 32, 3, 32, 3, 32, 3, 32, 3, 32, 3, 32, 3, 88, 2, 88, 2, 88, 2, 88, 2, 88, 2, 88, 2, 60, 0, 60, 0, 60, 0, 60, 0, 60, 0, 60, 0, 30, 0, 30, 0, 30, 0, 30, 0, 30, 0, 30, 0, 0, 0, 0, 0, 0, 53, 33};

        int FirstByteTmp, SecondByteTmp, ByteTmp;
        float MassCurrentsPhases[] = new float[30]; 

        for (int i = 0, j = 0; i < 30; i++, j += 2) {
            FirstByteTmp = (0x000000FF & ((int) bytes[5 + j]));
            SecondByteTmp = (0x000000FF & ((int) bytes[4 + j]));
            ByteTmp = (char) (FirstByteTmp << 8 | SecondByteTmp);
            MassCurrentsPhases[i] = (float) ByteTmp;
        }

        System.out.println(Arrays.toString(MassCurrentsPhases));
    }
}
it returns me this line:
[200.0, 40.0, 200.0, 200.0, 200.0, 200.0, 800.0, 800.0, 800.0, 800.0, 800.0, 800.0, 600.0, 600.0, 600.0, 600.0, 600.0, 600.0, 60.0, 60.0, 60.0, 60.0, 60.0, 60.0, 30.0, 30.0, 30.0, 30.0, 30.0, 30.0]

That is, the value is: -56, 0 = 200
The value is 40, 0, = 40
The value is 32, 3 =
800

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Saboteur, 2015-09-09
@Chvalov

int x=800
data[0] = (byte) x;
data[1] = (byte) (x>>> 8);
for larger numbers continue....
data[2] = (byte) (x>>> 16);
data[3] = (byte) (x>>> 24);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question