I have a byte array I want to assign as follows:
(byte)string.length()
string.getBytes()
Other than using a for loop, is there a quick way to initialize a byte array using bytes from two different variables?
util. Arrays. fill(). This method assigns the required byte value to the byte array in Java.
To make such an assignment from int to byte, we must use a cast. Java has a class Byte , which defines two constants to represent maximum and minimum values of the byte data type, Byte. MAX_VALUE and Byte. MIN_VALUE.
In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class. Implementation: Convert a String into a byte array and write it in a file. Example: Java.
Array setByte() method in Java Parameter: This method takes 3 parameters: array: This is an array of type Object which is to be updated. index: This is the index of the array which is to be updated. value: This is the byte value that is to be set at the given index of the given array.
You can use System.arrayCopy()
to copy your bytes:
String x = "xx";
byte[] out = new byte[x.getBytes().length()+1];
out[0] = (byte) (0xFF & x.getBytes().length());
System.arraycopy(x.getBytes(), 0, out, 1, x.length());
Though using something like a ByteArrayOutputStream
or a ByteBuffer
like other people suggested is probably a cleaner approach and will be better for your in the long run :-)
How about ByteBuffer
?
Example :
ByteBuffer bb = ByteBuffer.allocate(string.getBytes().length +1 );
bb.put((byte) string.length());
bb.put(string.getBytes());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With