开发者

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

开发者 https://www.devze.com 2023-01-30 14:10 出处:网络
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 Str

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 J开发者_StackOverflow社区ava?

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


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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号