Java:将String转换为字节数组,然后转换为long值,反之亦然 [英] Java: Conversion of String to byte array, then to long value and vice versa

查看:63
本文介绍了Java:将String转换为字节数组,然后转换为long值,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Basically, I'm looking for .NET's BitConverter.

我需要从String中获取字节,然后将其解析为长值并存储。之后,读取long值,解析为字节数组并创建原始String。如何用Java实现呢?

I need to get bytes from String, then parse them to long value and store it. After that, read long value, parse to byte array and create original String. How can I achieve this in Java?

编辑:有人已经问过类似的问题。我看起来更像是样本,然后是javadoc参考...

Someone did already ask similar question. I am looking more like for samples then javadoc reference ...

推荐答案

String 具有 getBytes 方法。您可以使用它来获取字节数组。

String has a getBytes method. You could use this to get a byte array.

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

To store the byte-array as longs, I suggest you wrap the byte-array in a ByteBuffer and use the asLongBuffer method.

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

To get the String back from an array of bytes, you could use the String(byte[] bytes) constructor.

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));

在ideone.com上看到它的运行情况

请注意,您可能想存储一个额外的整数,该数字告诉长整数-array实际上存储,因为字节数可能不是8的倍数。

Note that you probably want to store an extra integer telling how many bytes the long-array actually stores, since the number of bytes may not be a multiple of 8.

这篇关于Java:将String转换为字节数组,然后转换为long值,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆