简体   繁体   中英

convert int or long to byte hex array

what is the easiest way to convert an integer or a long value to a byte buffer?

example:

input : 325647187

output : {0x13,0x68,0xfb,0x53}

I have tried a ByteBuffer like this :

ByteBuffer buffer = ByteBuffer.allocate(4);
buffer.putLong(325647187);

byte[] x=buffer.array();

for(int i=0;i<x.length;i++)
{
    System.out.println(x[i]);
}

but I get exception

Exception in thread "main" java.nio.BufferOverflowException
    at java.nio.Buffer.nextPutIndex(Buffer.java:527)
    at java.nio.HeapByteBuffer.putLong(HeapByteBuffer.java:423)
    at MainApp.main(MainApp.java:11)

You allocated a 4 bytes buffer, but when calling putLong , you attempted to put 8 bytes in it. Hence the overflow. Calling ByteBuffer.allocate(8) will prevent the exception.

Alternately, if the encoded number is an integer (as in your snippet), it's enough to allocate 4 bytes and call putInt() .

you can try this for an easier way of converting:

so you have 325647187 as your input, we can then have something like this

byte[] bytes = ByteBuffer.allocate(4).putInt(325647187).array();

for (byte b : bytes) 
{
System.out.format("0x%x ", b);
}

for me this is(if not the most) an efficient way of converting to byte buffer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM