Packing bytes in long with | = gives unexpected results

I am trying to combine byte [] data into a long variable. But for some reason, the code is not working as I expected.

I have this byte array, the maximum size of which will be 8 bytes, which are 64 bits, the same size as the Long variable, so I'm trying to combine this array into a long variable.

public static void main(String[] args) {
    // TODO Auto-generated method stub

    byte[] data = new byte[]{
            (byte)0xD4,(byte)0x11,(byte)0x92,(byte)0x55,(byte)0xBC,(byte)0xF9
            };

    Long l = 0l;

    for (int i =0; i<6; i++){
        l |= data[i];           
        l <<=8;
        String lon = String.format("%064d", new BigInteger(Long.toBinaryString((long)l)));
        System.out.println(lon);
    }




}

Results:

1111111111111111111111111111111111111111111111111111010100000000000000
1111111111111111111111111111111111111111111101010000010001000000000000
11111111111111111111111111111111111111111111111111111001001000000000000
1111111111111111111111111111111111111111111001001001001010101000000000000
11111111111111111111111111111111111111111111111111111011110000000000
111111111111111111111111111111111111111111111111111111111001000000000000

-

111111111111111110101000001000110010010010101011011110011111001

0xD4,0x11,0x92,0x55,0xBC, 0xF9

+4
1

byte Java , long |= byte, byte , 1, byte .

:

 l |= (data[i] & 255)

int long. .


: " " , " 2" ?. .

:

byte b = (byte)0xB5;
long n = 0l;

n |= b; // analogous to your l |= data[i]

, n |= b n = n | b (JLS 15.26.2), .

, n | b. n b - .

JLS 15.22.1:

&, , | , (. 5.1.8), , (§5.6.2).

, 5.6.2, , . :

  1. (§5.1.2) , :

    • ...
    • , long, long.
    • ...

, , n - long, b long , 5.1.2. :

T - .

byte - long, ( ) , . ( 64 , ):

b = (byte)0xB5                     10110101
b widened to long  111 ... 1111111110110101
n                  000 ... 0000000000000000
n | b              111 ... 1111111110110101

n | b 0xFFFFFFFFFFFFFFB5, 0x00000000000000B5. , OR, 1, , , , , .

byte , Java , long | byte long | long .

, , :

n = n | (long)b;

, " ":

byte b = (byte)0xB5;
long n = 0l;

n |= (b & 255);

, b & 255.

, JLS 3.10.1 , 255 int.

byte & int. , , 5.6.2:

int.

, byte int. , :

(byte)0xB5                                10110101
promote to int    11111111111111111111111110110101  (sign extended)
255               00000000000000000000000011111111
&                 00000000000000000000000010110101

int, , , , 0.

n | the byte we just converted. int long, , :

b & 255                    00000000000000000000000010110101
convert to long  000 ... 0000000000000000000000000010110101
n                000 ... 0000000000000000000000000000000000
n | (b & 255)    000 ... 0000000000000000000000000010110101

.

b int 24 0, long , .

, , :

n = n | (long)((int)b & 255);

, , , 8 ( 8 ).

, 1 s. , , -1L 0L ( ).

+4

Source: https://habr.com/ru/post/1674050/


All Articles