Angel Sanchez Angel Sanchez - 2 months ago 13
Java Question

Save the length and the value of a string into a byte

I need to save in the first byte position of the number of characters that has a string. Then store the value of each of the characters in the following positions.

String cadena = new String ("Desarrollo");
byte valores[] = new byte [cadena.length()];
valores = cadena.getBytes();

Answer

Use a java.nio.ByteBuffer. Get the String representation as a byte[] based on some given character set. Write the size of the String first as an int, then write the byte[].

String cadena = new String("Desarollo");
byte[] bytes = cadena.getBytes("UTF-8");
ByteBuffer buffer = ByteBuffer.allocate(4 + bytes.length); // 4 being the size of an int in bytes
buffer.putInt(cadena.length());
buffer.put(bytes);

You can then get the underlying byte[] with

buffer.array();

You should write the String length as an int because byte has a maximum value of 127, which you will probably surpass very fast.

Comments