Hi guys,
it's the first time i have to solve these conversions and i'm having
too problems......
Excuse me for my english and my java inexperience,i need your help fpr
two situations:
1)How can i convert a string into an array of byte?
2) How can i convert an array of double into an array of byte?
What i care in the second problem is converting the array of double
according to a fixed format,like adding & beetwen two converted values
for giving me the possibility to rebuild original format of array
later.
Can you give me some code and comments to understand something?
I'm crazing and java documentation don't help me...............
Chris Uppal - 16 Jun 2006 13:09 GMT
> 1)How can i convert a string into an array of byte?
Normally you would use some fixed char encoding. E.g.
byte[] bytes = aString.getBytes("UTF-8");
> 2) How can i convert an array of double into an array of byte?
One way would be to use a DataOutputStream:
ByteArrayOutputStream bytestream =
new ByteArrayOutputStream();
DataOutputStream datastream =
new DataOutputStream(bytestream);
for (double d : aDoubleArray)
datastream.writeDouble(d);
datastream.flush();
byte[] bytes = bytestream.toByteArrray();
which will dump each double as it's raw 8-byte representation to the stream.
Since each double takes exactly 8-bytes regardless of its magnitude, you
probably don't need to include separators in the stream. If you want them
anyway, then you can add them usng the other methods of DataOutputStream.
Alternatively you can use Double.doubleToLongBits() to convert a double into a
64-bit long with the same bit pattern, and then use bitmanipulation to extract
the 8 individual bytes.
-- chris
Oliver Wong - 16 Jun 2006 17:56 GMT
> Hi guys,
> it's the first time i have to solve these conversions and i'm having
[quoted text clipped - 9 lines]
> for giving me the possibility to rebuild original format of array
> later.
Note that '&' is not a byte, but a character. It doesn't make sense to
add a '&' to a byte stream; instead, you'd add the ASCII byte-representation
of the '&' character, or the UTF-16LE byte-representation of the '&' (which
is different from the ASCII representation).
When designing your format, if you're going to have seperators, you have
to make sure that you can distinguish between the seperators and the values.
An alternative is to use fixed-length value encodings. For example,
always store all your double values as 4 bytes. Then you know where each
double starts or ends, without the use of seperators.
- Oliver