Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java convert long to 4 bytes

How do I convert long to 4 bytes? I am receiving some output from a C program and it uses unsigned long. I need to read this output and convert this to 4 bytes.

However, java uses signed long which is 64 bits. Is there any way to do this conversion?

like image 949
user1003385 Avatar asked Aug 31 '26 06:08

user1003385


2 Answers

To read 4 bytes as an unsigned 32-bit value, assuming it is little endian, the simplest thing to do is to use ByteBuffer

byte[] bytes = { 1,2,3,4 };
long l = ByteBuffer.wrap(bytes)
                   .order(ByteOrder.LITTLE_ENDIAN).getInt() & 0xFFFFFFFFL;

While l can be an signed 64-bit value it will only be between 0 and 2^^32-1 which is the range of a unsigned 32-bit value.

like image 132
Peter Lawrey Avatar answered Sep 03 '26 03:09

Peter Lawrey


You can use the java.nio.ByteBuffer. It can parse the long, and it does the byte ordering for you.

like image 43
Zagrev Avatar answered Sep 03 '26 04:09

Zagrev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!