Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One way to convert a long to a byte in Java is by using bitwise operators to extract the bits of the long and store them in a byte array. Here's an example:

long myLong = 12345L;
byte[] byteArr = new byte[8]; // long is 8 bytes long
for (int i = 0; i < 8; i++) {
    byteArr[i] = (byte) (myLong >> (i * 8)); // extract 8 bits at a time and store in byte array
}

In this example, we create a long variable myLong with a value of 12345L. We then create a byte array with a length of 8 to store the bytes of the long.

Next, we use a for loop to iterate over each byte in the array. For each byte, we use bitwise right-shift (>>) to extract the 8 bits of the long corresponding to that byte position. We then cast this value to a byte and store it in the byte array.

After running this code, we would have a byte array with the bytes of the long value [0, 0, 0, 0, 0, 0, 48, -103]. The last two values are the bytes representing the long value 12345L in two's complement notation.