我如何将 Long 转换为 byte[] 并返回到 java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4485128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I convert Long to byte[] and back in java
提问by Emre801
How do I convert a long
to a byte[]
and back in Java?
如何在 Java 中将long
a转换为 abyte[]
并返回?
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
.
我正在尝试将 a 转换long
为 abyte[]
以便我能够byte[]
通过 TCP 连接发送。另一方面,我想byte[]
将其转换回double
.
采纳答案by Brad Mace
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:
或者包裹在一个类中以避免重复创建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 answerfirst 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.
由于它变得如此流行,我只想提一下,我认为在绝大多数情况下,您最好使用像 Guava 这样的库。如果您对库有一些奇怪的反对意见,您可能应该首先考虑本机 Java 解决方案的这个答案。我认为我的回答真正要解决的主要问题是您不必自己担心系统的字节序。
回答by Peter Lawrey
Why do you need the byte[]? why not just write it to the socket?
为什么需要字节[]?为什么不直接将其写入套接字?
I assume you mean longrather than Long, the latter needs to allow for null values.
我假设您的意思是long而不是Long,后者需要允许空值。
DataOutputStream dos = new DataOutputStream(
new BufferedOutputStream(socket.getOutputStream()));
dos.writeLong(longValue);
DataInputStream dis = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));
long longValue = dis.readLong();
回答by Matt Solnit
If you are already using an OutputStream
to write to the socket, then DataOutputStreammight be a good fit. Here is an example:
如果您已经使用 anOutputStream
写入套接字,那么DataOutputStream可能是一个不错的选择。下面是一个例子:
// 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 DataInputStreamon the receiving side.
还有类似的方法short
,int
,float
,等你可以再使用DataInputStream所接收方。
回答by Michael Konietzka
Just write the long to a DataOutputStreamwith an underlying ByteArrayOutputStream. From the ByteArrayOutputStream you can get the byte-array via toByteArray():
只需将 long 写入带有底层ByteArrayOutputStream的DataOutputStream。从 ByteArrayOutputStream 您可以通过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 Socketsocket
and its streams
提示:对于 TCP,您不需要手动输入 byte[]。您将使用Socketsocket
及其流
OutputStream os=socket.getOutputStream();
DataOutputStream dos=new DataOutputStream(os);
dos.writeLong(l);
//etc ..
instead.
反而。
回答by 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;
}
回答by 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
您可以使用 org.apache.hadoop.hbase.util.Bytes http://hbase.apache.org/apidocs/org/apache/hadoop/hbase/util/Bytes.html 中的实现
The source code is here:
源代码在这里:
Look for the toLong and toBytes methods.
查找 toLong 和 toBytes 方法。
I believe the software license allows you to take parts of the code and use it but please verify that.
我相信软件许可证允许您获取部分代码并使用它,但请验证这一点。
回答by Sonson123
You could use the Byte conversion methodsfrom Google Guava.
Example:
例子:
byte[] bytes = Longs.toByteArray(12345L);
回答by Michael B?ckling
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:
如果您正在寻找快速展开的版本,这应该可以解决问题,假设一个名为“b”的字节数组的长度为 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
long -> byte[]作为上述内容的精确对应物
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)};
回答by Wytze
I tested the ByteBuffer method against plain bitwise operations but the latter is significantly faster.
我针对普通的按位运算测试了 ByteBuffer 方法,但后者明显更快。
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[] bytes, final int offset) {
long result = 0;
for (int i = offset; i < Long.BYTES + offset; i++) {
result <<= Long.BYTES;
result |= (bytes[i] & 0xFF);
}
return result;
}
回答by 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.
您可以简单地使用 String 作为中间体。请注意,这将为您提供正确的结果,即使使用 String 似乎可能会产生错误的结果,只要您知道您正在使用“正常”字符串。这是一种提高效率并使代码更简单的方法,作为回报,必须对其操作的数据字符串使用一些假设。
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.
使用此方法的缺点:如果您在 ASCII 表的开头使用一些 ASCII 字符,如这些符号,以下行可能会失败,但让我们面对现实 - 无论如何您可能永远不会使用它们。
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[]:
从 Long 到 byte[]:
byte[] arr = String.valueOf(longVar).getBytes();
from byte[] to Long:
从字节[]到长:
long longVar = Long.valueOf(new String(byteArr)).longValue();