Reputation: 111
based on this array :
final char[] charValue = { 'u', ' ', '}','+' };
i want to print the double value and the ascii value from it in Java. i can't find a proper solution for that in internet. I just found how to convert a single Character into Integer value. But what about many characters? the main problem is, i have a large char[] and some double and int values are stored in. for double values they are stored within 4 bytes size and integer 1 or 2 bytes so i have to read all this and convert into double or integer.
Thanks for you help
Upvotes: 0
Views: 1231
Reputation: 109613
When java was designed, there was C char
being used for binary bytes and text.
Java made a clear separation between binary data (byte[], InputStream/OutputStream
) and Unicode text (char, String, Reader/Writer
). Hence Java has full Unicode support. The binary data, byte[]
, need information: their used encoding, in order to be convertable to text: char[]/String
.
In Java a char[]
will rarely be used (as in C/C++), and it seems byte[]
is intended, as you mention 4 elements to be used for an int
etcetera. A char is 16 bits, containing UTF-16 text.
For this case one can use a ByteBuffer either wrapping a byte[]
or being taken from a memory mapped file.
Writing
ByteBuffer buf = ByteBuffer.allocate(13); // 13 bytes
buf.order(ByteOrder.LITTLE_ENDIAN); // Intel order
buf.putInt(42); // at 0
buf.putDouble(Math.PI); // at 4
buf.put((byte) '0'); // at 12
buf.putDouble(4, 3.0); // at 4 overwrite PI
byte[] bytes = buf.array();
Reading
ByteBuffer buf = ByteBuffer.wrap(bytes);
buf.order(ByteOrder.LITTLE_ENDIAN); // Intel order
int a = buf.getInt();
double b = buf.getDouble();
byte c = buf.get();
Upvotes: 1