How to Initialize a Byte Array in Java

How do I initialize a byte array in Java?

You can use an utility function to convert from the familiar hexa string to a byte[].
When used to define a final static constant, the performance cost is irrelevant.

Since Java 17

There's now java.util.HexFormat which lets you do

byte[] CDRIVES = HexFormat.of().parseHex("e04fd020ea3a6910a2d808002b30309d");

This utility class lets you specify a format which is handy if you find other formats easier to read or when you're copy-pasting from a reference source:

byte[] CDRIVES = HexFormat.ofDelimiter(":")
.parseHex("e0:4f:d0:20:ea:3a:69:10:a2:d8:08:00:2b:30:30:9d");

Before Java 17

I'd suggest you use the function defined by Dave L in Convert a string representation of a hex dump to a byte array using Java?

byte[] CDRIVES = hexStringToByteArray("e04fd020ea3a6910a2d808002b30309d");

I insert it here for maximum readability :

public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}

how to initialize byte array in Java?

This should work

  byte[] bytes = {69, 121, 101, 45, 62, 118, 101, 114, (byte) 196, (byte) 195, 61, 101, 98};

Byte can hold upto -128 to 127 only. Some of the values are exceeding the limit of a byte value. So you need to cast them to byte.

Initializing byte array in java

I used a ByteArrayInputStream and System.arraycopy to do the job:

package bom;

import java.io.ByteArrayInputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Bom {

public static void main(String[] args) {
try {
new Bom().go();
} catch (Exception ex) {
Logger.getLogger(Bom.class.getName()).log(Level.SEVERE, null, ex);
}
}

private void go() throws Exception {
//create data with BOM header:
byte[] byteArrayBom = {(byte) 0xEF, (byte) 0xBB, (byte) 0xBF, 65, 66, 67};

ByteArrayInputStream bais = new ByteArrayInputStream(byteArrayBom);
if (byteArrayBom.length >= 3) {
//read the first 3 bytes to detect BOM header:
int b00 = bais.read();
int b01 = bais.read();
int b02 = bais.read();
if (b00 == 239 && b01 == 187 && b02 == 191) {
//BOM detected. create new byte[] for bytes without BOM:
byte[] contentWithoutBom = new byte[byteArrayBom.length - 3];

//copy byte array without the first 3 bytes:
System.arraycopy(byteArrayBom, 3, contentWithoutBom, 0, byteArrayBom.length - 3);

//let's see what we have:
System.out.println(new String(contentWithoutBom)); //ABC

for (int i = 0; i < contentWithoutBom.length; i++) {
System.out.println(contentWithoutBom[i]); //65, 66 67
}
}
}
}
}

How to initailize byte array of 100 bytes in java with all 0's

A new byte array will automatically be initialized with all zeroes. You don't have to do anything.

The more general approach to initializing with other values, is to use the Arrays class.

import java.util.Arrays;

byte[] bytes = new byte[100];
Arrays.fill( bytes, (byte) 1 );

Initialise and return a byte array in java

You need to use this:

 byte[] temp = new byte[some_const];
ret = foo(temp);

boolean foo(byte[] temp)
{
//fill array
}

or

 byte[] temp = null;
temp = foo(temp);

byte[] foo(byte[] temp)
{ temp = new byte[some_const];
//fill array
return temp;
}

How to create an array of byte arrays in java

To address some confusion about "arrays of arrays" and 2D arrays:

Java doesn't really have 2D arrays. At least, not in the way many people think of them, where they look like a matrix, and you have rows and columns and the same number of elements in each row.

You can use an "array of arrays" as a 2D array. If you want an array of 5 x 8 integers, you can say

int[][] arr = new int[5][8];

But Java does not enforce the "matrix-ness" or "2D-ness" of an array. What it gives you is an array of 5 references, each of which refers to another array of integers. Each reference starts out referring to an array of 8 integers, but this is not enforced; you could later say

arr[2] = new int[113];

or

arr[2] = null;

and now your array is no longer really a 2D array (as we usually think of it), but Java will not stop you from doing that.

So while you may often see something like

byte[][] 

used in textbooks to create a 2D array, it's the same syntax as an array of arrays, and Java actually treats it as an array of arrays, not all of which have to be the same size.

If you want to create an array whose elements will eventually be arrays, but that are null for now, you can do it like this:

byte[][] bytesArray = new byte[10][];

which sets bytesArray to an array of 10 null references, any one of which could be set later:

bytesArray[4] = new byte[17];

That would be the way to start, if you want a "ragged array" of arrays that aren't all the same length.



Related Topics



Leave a reply



Submit