Java: Conversion of String to byte array, then to

2019-08-13 15:22发布

问题:

Basically, I'm looking for .NET's 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?

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

回答1:

String has a getBytes method. 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.

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

See it in action at ideone.com

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.