0

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 ?

thotheolh
  • 7,040
  • 7
  • 33
  • 49
  • 1
    have you tried to use a step-by-step debugger to see what's put in a,b,c? – jhamon Apr 18 '19 at 07:38
  • 1
    and put the complete code. For now, the declaration and call of `doSomething`is not valid java code. – jhamon Apr 18 '19 at 07:40
  • 2
    Nota that with `offset > length` your loop in `toHexString` ends immediately. – piet.t Apr 18 '19 at 07:44
  • Ops. Forgot about the `offset > length` portion. Please put it as the main answer so I can close it. Thanks so much for pointing it out. – thotheolh Apr 18 '19 at 07:49

1 Answers1

1

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
Hemant Patel
  • 3,160
  • 1
  • 20
  • 29