从java方法返回一个字节数组

Pra*_*nay 1 java string

我有一个字节数组,我传递给一个函数nibbleSwap.nibbleSwap对于阵列中的每个字节值,将第4个位与第2个4位进行交换.交换后,我必须返回交换的字节值.如果我只是打印字节数组我能够得到正确的值但是当我返回交换的字节数组时,它不会打印正确的值.
我的代码是这样的:

private static byte[] nibbleSwap(byte []inByte){
        int []nibble0 = new int[inByte.length];
        int []nibble1 = new int[inByte.length];
        byte []b = new byte[inByte.length];

        for(int i=0;i<inByte.length;i++)
        {
                nibble0[i] = (inByte[i] << 4) & 0xf0;
                 nibble1[i] = (inByte[i] >>> 4) & 0x0f;
                b[i] =(byte) ((nibble0[i] | nibble1[i]));
                /*System.out.printf(" swa%x ",b[i]); ---   if i do this by changing the return to void i get the correct output.
        */
                   }

        return b;
    }  
Run Code Online (Sandbox Code Playgroud)

例如.valuebyte[]contains:91,19,38,14,47,21,11 我希望函数返回一个包含的数组19,91,83,41,74,12,11.另外,我可以通过将返回类型更改为String来将其作为String返回,因为当我这样做并打印它时,我得到了交换字节值的整数值吗?

请帮忙!!
Pranay

NPE*_*NPE 5

代码完全按照您的要求对您的测试数据执行,当然,前提是值(91,19,38,14,47,21,11)为十六进制(0x91,0x19等) .

我用以下代码来调用你的函数:

public static void main(String[] args) {
    byte[] swapped = nibbleSwap(new byte[]{(byte)0x91, 0x19, 0x38, 0x14, 0x47, 0x21, 0x11});
    for (byte b : swapped) {
        System.out.printf("%x ", b);
    }
    System.out.println();
}
Run Code Online (Sandbox Code Playgroud)

打印出:

19 91 83 41 74 12 11 
Run Code Online (Sandbox Code Playgroud)

要将结果作为字符串返回,您可以使用以下行中的内容:

public class NibbleSwap {

    private static String nibbleSwap(byte []inByte){
        String ret = "";
        for(int i = 0; i < inByte.length; i++)
        {
                int nibble0 = (inByte[i] << 4) & 0xf0;
                int nibble1 = (inByte[i] >>> 4) & 0x0f;
                byte b = (byte)((nibble0 | nibble1));
                ret += String.format("%x ", b);
        }

        return ret;
    }  

    public static void main(String[] args) {
        System.out.println(nibbleSwap(new byte[]{(byte)0x91,0x19,0x38,0x14,0x47,0x21,0x11}));
    }

}
Run Code Online (Sandbox Code Playgroud)