ChatGPT解决这个技术问题 Extra ChatGPT

How do I convert Long to byte[] and back in java

How do I convert a long to a byte[] and back in Java?

I'm trying convert a long to a byte[] so that I will be able to send the byte[] over a TCP connection. On the other side I want to take that byte[] and convert it back into a double.

Another alternative will be Maps.transformValues, a general tooling for converting collections. docs.guava-libraries.googlecode.com/git-history/release/javadoc/…
See also stackoverflow.com/q/27559449/32453 if your goal is to convert a long into the fewest number of Base64 chars.

C
Community
public byte[] longToBytes(long x) {
    ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
    buffer.putLong(x);
    return buffer.array();
}

public long bytesToLong(byte[] bytes) {
    ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
    buffer.put(bytes);
    buffer.flip();//need flip 
    return buffer.getLong();
}

Or wrapped in a class to avoid repeatedly creating ByteBuffers:

public class ByteUtils {
    private static ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);    

    public static byte[] longToBytes(long x) {
        buffer.putLong(0, x);
        return buffer.array();
    }

    public static long bytesToLong(byte[] bytes) {
        buffer.put(bytes, 0, bytes.length);
        buffer.flip();//need flip 
        return buffer.getLong();
    }
}

Since this is getting so popular, I just want to mention that I think you're better off using a library like Guava in the vast majority of cases. And if you have some strange opposition to libraries, you should probably consider this answer first for native java solutions. I think the main thing my answer really has going for it is that you don't have to worry about the endian-ness of the system yourself.


Clever ... but you create and discard a temporary ByteBuffer for each conversion. Not good if you are sending multiple longs per message and/or lots of messages.
@Stephen - I was just doing enough to demonstrate how to use ByteBuffer, but I went ahead and added an example of using it in a utility class.
I think the bytesToLong() here would fail as the position after the put is at the end of the buffer, not the beginning. I think you'd get a buffer underflow exception.
Pre-Java 8, you can use Long.SIZE/Byte.SIZE instead of Long.BYTES to avoid a magic number.
The reuse of that bytebuffer is highly problematic, and not just for the thread-safety reasons as others commented. Not only would a '.clear()' be needed in between, but what's not obvious is that calling .array() on the ByteBuffer is returning the backing array versus a copy. Thus if you call repeatedly and hold onto the other results, they're actually all the same array that repeatedly is overwriting the previous values. The hadoop link in a comment below is the most performant and avoids any of these issues.
S
Sonson123

You could use the Byte conversion methods from Google Guava.

Example:

byte[] bytes = Longs.toByteArray(12345L);

W
Wytze

I tested the ByteBuffer method against plain bitwise operations but the latter is significantly faster.

public static byte[] longToBytes(long l) {
    byte[] result = new byte[8];
    for (int i = 7; i >= 0; i--) {
        result[i] = (byte)(l & 0xFF);
        l >>= 8;
    }
    return result;
}

public static long bytesToLong(final byte[] b) {
    long result = 0;
    for (int i = 0; i < 8; i++) {
        result <<= 8;
        result |= (b[i] & 0xFF);
    }
    return result;
}

For Java 8+ we can use the static variables that were added:

public static byte[] longToBytes(long l) {
    byte[] result = new byte[Long.BYTES];
    for (int i = Long.BYTES - 1; i >= 0; i--) {
        result[i] = (byte)(l & 0xFF);
        l >>= Byte.SIZE;
    }
    return result;
}

public static long bytesToLong(final byte[] b) {
    long result = 0;
    for (int i = 0; i < Long.BYTES; i++) {
        result <<= Byte.SIZE;
        result |= (b[i] & 0xFF);
    }
    return result;
}

Instead of result |= (b[i] & 0xFF); We could simply use result |= b[i]; as and with 0xFF for a bit doesnt modify anything.
@Vipul The bitwise-and does matter because when doing just result |= b[i] the byte value will first be converted to long which does sign extension. A byte with value -128 (hex 0x80) will turn into a long with value -128 (hex 0xFFFF FFFF FFFF FF80). First after the conversion are the values or:ed together. Using bitwise-and protects against this by first converting the byte to an int and cutting off the sign extension: (byte)0x80 & 0xFF ==> (int)0xFFFF FF80 & 0xFF ==> (int) 0x80. Why bytes are signed in java is a bit of a mystery to me, but I guess that it's to fit in with other types.
@Brainstorm I tried case -128 with |= b[i] and with |= (b[i] & 0xFF) and the results are the same !!
The problem is that the byte gets promoted before the shift is applied which causes strange problems with the sign bit. Therefore we first and (&) it with 0xFF to get the correct value to shift.
I try to convert this data (data = new byte[]{(byte) 0xDB, (byte) 0xA7, 0x53, (byte) 0xF8, (byte) 0xA8, 0x0C, 0x66, 0x8}; ) to long, but it return false value -2619032330856274424, the expected value is 989231983928329832
D
Dreamspace President

If you are looking for a fast unrolled version, this should do the trick, assuming a byte array called "b" with a length of 8:

byte[] -> long

long l = ((long) b[7] << 56)
       | ((long) b[6] & 0xff) << 48
       | ((long) b[5] & 0xff) << 40
       | ((long) b[4] & 0xff) << 32
       | ((long) b[3] & 0xff) << 24
       | ((long) b[2] & 0xff) << 16
       | ((long) b[1] & 0xff) << 8
       | ((long) b[0] & 0xff);

long -> byte[] as an exact counterpart to the above

byte[] b = new byte[] {
       (byte) lng,
       (byte) (lng >> 8),
       (byte) (lng >> 16),
       (byte) (lng >> 24),
       (byte) (lng >> 32),
       (byte) (lng >> 40),
       (byte) (lng >> 48),
       (byte) (lng >> 56)};

Thank you, the best!
This assumes little-endian byte order, and the long -> byte[] code added by someone else in a subsequent edit fails for negative numbers :-/
E
Evan Knowles

Why do you need the byte[]? why not just write it to the socket?

I assume you mean long rather than Long, the latter needs to allow for null values.

DataOutputStream dos = new DataOutputStream(
     new BufferedOutputStream(socket.getOutputStream()));
dos.writeLong(longValue);

DataInputStream dis = new DataInputStream(
     new BufferedInputStream(socket.getInputStream()));
long longValue = dis.readLong();

He asked how you convert to byte[] and back. Good answer but didn't answer the question. You ask why because you assume it is unnecessary but that's a wrong assumption. What if he is doing cross-language or cross-platform? DataOutputStream won't help you there.
If he's doing cross-language or cross-platform, then sending the bytes in a known order is important. This method does that (it writes them "high byte first") according to the docs. The accepted answer does not (it writes them in the "current order" according to the docs). The question states that he wants to send them over a TCP connection. The byte[] is just a means to that end.
@IanMcLaird The accepted answer does use a known order. It creates a new ByteBuffer which according to the docs "The initial order of a byte buffer is always BIG_ENDIAN.
H
HexllioN

I find this method to be most friendly.

var b = BigInteger.valueOf(x).toByteArray();

var l = new BigInteger(b);

M
Michael Konietzka

Just write the long to a DataOutputStream with an underlying ByteArrayOutputStream. From the ByteArrayOutputStream you can get the byte-array via toByteArray():

class Main
{

        public static byte[] long2byte(long l) throws IOException
        {
        ByteArrayOutputStream baos=new ByteArrayOutputStream(Long.SIZE/8);
        DataOutputStream dos=new DataOutputStream(baos);
        dos.writeLong(l);
        byte[] result=baos.toByteArray();
        dos.close();    
        return result;
        }


        public static long byte2long(byte[] b) throws IOException
        {
        ByteArrayInputStream baos=new ByteArrayInputStream(b);
        DataInputStream dos=new DataInputStream(baos);
        long result=dos.readLong();
        dos.close();
        return result;
        }


        public static void main (String[] args) throws java.lang.Exception
        {

         long l=123456L;
         byte[] b=long2byte(l);
         System.out.println(l+": "+byte2long(b));       
        }
}

Works for other primitives accordingly.

Hint: For TCP you do not need the byte[] manually. You will use a Socket socket and its streams

OutputStream os=socket.getOutputStream(); 
DataOutputStream dos=new DataOutputStream(os);
dos.writeLong(l);
//etc ..

instead.


M
Marquez

You could use the implementation in org.apache.hadoop.hbase.util.Bytes http://hbase.apache.org/apidocs/org/apache/hadoop/hbase/util/Bytes.html

The source code is here:

http://grepcode.com/file/repository.cloudera.com/content/repositories/releases/com.cloudera.hbase/hbase/0.89.20100924-28/org/apache/hadoop/hbase/util/Bytes.java#Bytes.toBytes%28long%29

Look for the toLong and toBytes methods.

I believe the software license allows you to take parts of the code and use it but please verify that.


Why does that implementation use XOR (^=) instead of OR? github.com/apache/hbase/blob/master/hbase-common/src/main/java/…
m
maziar
 public static long bytesToLong(byte[] bytes) {
        if (bytes.length > 8) {
            throw new IllegalMethodParameterException("byte should not be more than 8 bytes");

        }
        long r = 0;
        for (int i = 0; i < bytes.length; i++) {
            r = r << 8;
            r += bytes[i];
        }

        return r;
    }



public static byte[] longToBytes(long l) {
        ArrayList<Byte> bytes = new ArrayList<Byte>();
        while (l != 0) {
            bytes.add((byte) (l % (0xff + 1)));
            l = l >> 8;
        }
        byte[] bytesp = new byte[bytes.size()];
        for (int i = bytes.size() - 1, j = 0; i >= 0; i--, j++) {
            bytesp[j] = bytes.get(i);
        }
        return bytesp;
    }

you can skip the ArrayList: public static byte[] longToBytes(long l) { long num = l; byte[] bytes = new byte[8]; for (int i = bytes.length - 1, i >= 0; i--) { bytes[i] = (byte)(num & 0xff); num >>= 8; } return bytesp; }
The original method doesn't work with negative numbers as it gets in an infinite loop in while (l != 0), @eckes's method doesn't work with numbers over 127 because he doesn't account for bytes going negative over 127 cause they are signed.
Y
Yonatan Nir

I will add another answer which is the fastest one possible ׂ(yes, even more than the accepted answer), BUT it will not work for every single case. HOWEVER, it WILL work for every conceivable scenario:

You can simply use String as intermediate. Note, this WILL give you the correct result even though it seems like using String might yield the wrong results AS LONG AS YOU KNOW YOU'RE WORKING WITH "NORMAL" STRINGS. This is a method to increase effectiveness and make the code simpler which in return must use some assumptions on the data strings it operates on.

Con of using this method: If you're working with some ASCII characters like these symbols in the beginning of the ASCII table, the following lines might fail, but let's face it - you probably will never use them anyway.

Pro of using this method: Remember that most people usually work with some normal strings without any unusual characters and then the method is the simplest and fastest way to go.

from Long to byte[]:

byte[] arr = String.valueOf(longVar).getBytes();

from byte[] to Long:

long longVar = Long.valueOf(new String(byteArr)).longValue();

Sorry for necroposting, but that's just wrong. E. g. String.valueOf(0).getBytes()[0] == 0x30. Surprise! String#getBytes will return ASCII-encoded digit symbols, not digits: '0' != 0, but '0' == 0x30
Well maybe if you had read my entire answer then you'd seen I have warned about it in the answer itself..
Ah, I missed the point that intermediate byte[] data is treated as (almost) opaque. Your trick will do for this scenario.
A
Artem Botnev

Kotlin extensions for Long and ByteArray types:

fun Long.toByteArray() = numberToByteArray(Long.SIZE_BYTES) { putLong(this@toByteArray) }

private inline fun numberToByteArray(size: Int, bufferFun: ByteBuffer.() -> ByteBuffer): ByteArray =
    ByteBuffer.allocate(size).bufferFun().array()

@Throws(NumberFormatException::class)
fun ByteArray.toLong(): Long = toNumeric(Long.SIZE_BYTES) { long }

@Throws(NumberFormatException::class)
private inline fun <reified T: Number> ByteArray.toNumeric(size: Int, bufferFun: ByteBuffer.() -> T): T {
    if (this.size != size) throw NumberFormatException("${T::class.java.simpleName} value must contains $size bytes")

    return ByteBuffer.wrap(this).bufferFun()
}

You can see full code in my library https://github.com/ArtemBotnev/low-level-extensions


M
Matt Solnit

If you are already using an OutputStream to write to the socket, then DataOutputStream might be a good fit. Here is an example:

// Assumes you are currently working with a SocketOutputStream.

SocketOutputStream outputStream = ...
long longValue = ...

DataOutputStream dataOutputStream = new DataOutputStream(outputStream);

dataOutputStream.writeLong(longValue);
dataOutputStream.flush();

There are similar methods for short, int, float, etc. You can then use DataInputStream on the receiving side.


D
Dave Jarvis

Here's another way to convert byte[] to long using Java 8 or newer:

private static int bytesToInt(final byte[] bytes, final int offset) {
    assert offset + Integer.BYTES <= bytes.length;

    return (bytes[offset + Integer.BYTES - 1] & 0xFF) |
            (bytes[offset + Integer.BYTES - 2] & 0xFF) << Byte.SIZE |
            (bytes[offset + Integer.BYTES - 3] & 0xFF) << Byte.SIZE * 2 |
            (bytes[offset + Integer.BYTES - 4] & 0xFF) << Byte.SIZE * 3;
}

private static long bytesToLong(final byte[] bytes, final int offset) {
    return toUnsignedLong(bytesToInt(bytes, offset)) << Integer.SIZE |
            toUnsignedLong(bytesToInt(bytes, offset + Integer.BYTES));
}

Converting a long can be expressed as the high- and low-order bits of two integer values subject to a bitwise-OR. Note that the toUnsignedLong is from the Integer class and the first call to toUnsignedLong may be superfluous.

The opposite conversion can be unrolled as well, as others have mentioned.


Q
Quân Anh Mai

From Java 9, the best approach is to use VarHandle, which will read from the byte array as if it is a long array, for performance make the VarHandle instance a static final field.

static final VarHandle HANDLE = MethodHandles.byteArrayViewVarHandle(Long.TYPE.arrayType(), ByteOrder.nativeOrder());

static long bytesToLong(byte[] bytes, int offset) {
    return (long)HANDLE.get(bytes, offset);
}

static void longToBytes(byte[] bytes, int offset, long value) {
    HANDLE.set(bytes, offset, value);
}

E
Eric Aya

All of the current answers are more complicated than they need to be and I’d hate for anyone locating this thread to walk away without a more concise option.

You can do both of these conversions in a single line.

byte[] to long:

ByteBuffer.wrap(yourBytes).getLong();

long to byte[]:

ByteBuffer.wrap(new byte[8]).putLong(yourLong).array();

A
Abdel
static byte[] longToBytes(Long l) {
    return (l + "").getBytes(StandardCharsets.UTF_8);
}

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.