Angel Sanchez Angel Sanchez - 1 year ago 75
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 Source

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

You can then get the underlying byte[] with


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download