简体   繁体   English

Java:将字符串转换为字节数组,然后转换为长值,反之亦然

[英]Java: Conversion of String to byte array, then to long value and vice versa

Basically, I'm looking for .NET's BitConverter .基本上,我正在寻找 .NET 的BitConverter

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?我如何在 Java 中实现这一点?

Edit: Someone did already ask similar question.编辑:有人已经问过类似的问题。 I am looking more like for samples then javadoc reference ...我看起来更像是示例,然后是 javadoc 参考...

String has a getBytes method. String有一个getBytes方法。 You could use this to get a byte array.您可以使用它来获取字节数组。

To store the byte-array as longs, I suggest you wrap the byte-array in a ByteBuffer and use the asLongBuffer method.要将字节数组存储为 long,我建议您将字节数组包装在ByteBuffer并使用asLongBuffer方法。

To get the String back from an array of bytes, you could use the String(byte[] bytes) constructor.要从字节数组中取回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));

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.请注意,您可能想要存储一个额外的整数,告诉长数组实际存储的字节数,因为字节数可能不是 8 的倍数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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