Java:将String转换为字节数组,然后转换为long值,反之亦然

时间:2010-12-13 18:25:01

标签: java bytearray

基本上,我正在寻找.NET的 BitConverter

我需要从String中获取字节,然后将它们解析为long值并存储它。之后,读取long值,解析为byte数组并创建原始String。我怎样才能在Java中实现这一目标?

编辑:有人确实问了类似的问题。我看起来更喜欢样本然后javadoc引用...

1 个答案:

答案 0 :(得分:2)

StringgetBytes方法。您可以使用它来获取字节数组。

要将字节数组存储为long,我建议您将字节数组包装在ByteBuffer中并使用asLongBuffer方法。

要从字节数组中取回String,可以使用String(byte[] bytes)构造函数。

String input = "hello long world";

byte[] bytes = input.getBytes();
LongBuffer tmpBuf = ByteBuffer.wrap(bytes).asLongBuffer();

long[] lArr = new long[tmpBuf.remaining()];
for (int i = 0; i < lArr.length; i++)
    lArr[i] = tmpBuf.get();

System.out.println(input);
System.out.println(Arrays.toString(lArr));
// store longs...

// ...load longs
long[] longs = { 7522537965568945263L, 7955362964116237412L };
byte[] inputBytes = new byte[longs.length * 8];
ByteBuffer bbuf = ByteBuffer.wrap(inputBytes);
for (long l : longs)
    bbuf.putLong(l);
System.out.println(new String(inputBytes));

See it in action at ideone.com

请注意,您可能希望存储一个额外的整数,以告知长数组实际存储的字节数,因为字节数可能不是8的倍数。

相关问题