Reputation: 7450
I am trying to access data in byte array used as parameters when passed into a method which I am not getting any data from.
Below is an example:
public class Main {
public static void main(String[] args) {
byte[] b = new byte[9];
SomeOtherClass.doSomething(b, 0, b, 3, b, 6);
}
// Credits to StackOverFlow post for modified method (https://stackoverflow.com/a/9855338/476467)
public static String toHexString(byte[] bytes, int offset, int length) {
char[] hexArray = "0123456789ABCDEF".toCharArray();
char[] hexChars = new char[length * 2];
for (int j = offset; j < length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
}
public class SomeOtherClass {
public static void doSomething(byte[] a, int offA, byte[] b, int offB, byte[] c, int offC) {
// Set a
a[offA] = (byte) 0x68;
a[offA+1] = (byte) 0x65;
a[offA+2] = (byte) 0x6c;
// Set b
b[offB] = (byte) 0x6c;
b[offB+1] = (byte) 0x6f;
b[offB+2] = (byte) 0x77;
// Set c
c[offC] = (byte) 0x6f;
c[offC+1] = (byte) 0x72;
c[offC+2] = (byte) 0x6c;
// Print the byte buffers for buffer a, b, c
System.out.println("buffer a: " + Main.toHexString(a, offA, 3));
System.out.println("buffer b: " + Main.toHexString(b, offB, 3));
System.out.println("buffer c: " + Main.toHexString(c, offC, 3));
}
}
After executing, I am getting:
buffer a:
buffer b:
buffer c:
No variables are printed in their hexadecimal format in the output despite having placed values into them.
I am certain the toHexString()
method is working as I have used it frequently and it always work and I doubt it is the toHexString()
having any problems.
How do I get the hexadecimal strings of the values to be visible ?
Upvotes: 0
Views: 112
Reputation: 3260
Just changed your loop in the method toHexString
as:
for (int j = 0; j < length; j++) {
int v = bytes[offset + j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
Output:
buffer a: 68656C
buffer b: 6C6F77
buffer c: 6F726C
Upvotes: 1