Ask Your Question
1

How can one convert a long to a byte in Java?

asked 2023-06-22 06:02:00 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-06-22 06:15:01 +0000

lalupa gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-22 06:02:00 +0000

Seen: 18 times

Last updated: Jun 22 '23