1

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 ...

4
  • 1
    What's wrong with javadoc reference? Commented Dec 13, 2010 at 18:37
  • 1
    Why would you convert byte[] to long[] to store them. The problem is that long must be multiple of 8 bytes long, so if your string is not a multiple of 8, you will have to record the length as well. Why not save the byte[] as a byte[], this is the simplest and more efficient. Commented Dec 13, 2010 at 18:43
  • @The Elite Gentleman It's something that I did myself and wasn't able to figure out how to solve described problem though :) Commented Dec 13, 2010 at 18:49
  • 1
    @The javadoc, like most API documentation, is much better at answering "what does this do?" than it is at answering "how do I do this?". Commented Dec 13, 2010 at 18:57

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

10 Comments

And how do you get original string back from bytes?
How would you parse the long back to byte array?
what are those long numbers? if I change string to "Hello joe world" result is again "hello long world"
I manually entered the numbers corresponding to "hello long world" to simulate a "load longs from disk" :-) You could replace longs = { ... with longs = lArr; instead to short-cut it :)
OK, so let's get original string. I updated code to: long[] longs = lArr; With "hello long world" it works, with "hello joe world" it doesn't. Try it yourself :)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.