Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning to a byte array in Java

I have a byte array I want to assign as follows:

  • First byte specifies the length of the string: (byte)string.length()
  • 2nd - Last bytes contain string data from string.getBytes()

Other than using a for loop, is there a quick way to initialize a byte array using bytes from two different variables?

like image 854
fredley Avatar asked Jan 06 '11 19:01

fredley


People also ask

How do you assign a byte array?

util. Arrays. fill(). This method assigns the required byte value to the byte array in Java.

How do you assign a byte value 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.

How do you create a byte array in Java?

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.

How do you assign a byte value?

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.


2 Answers

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 :-)

like image 160
Guss Avatar answered Oct 05 '22 23:10

Guss


How about ByteBuffer ?

Example :

    ByteBuffer bb = ByteBuffer.allocate(string.getBytes().length +1 );
    bb.put((byte) string.length());
    bb.put(string.getBytes());
like image 26
jmj Avatar answered Oct 05 '22 23:10

jmj