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

标签 java string

我有一个字节数组,我正在将其传递给函数 nibbleSwapnibbleSwap 为数组中的每个字节值交换前 4 位和后 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;
    }  

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

请帮忙!!
呼吸机

最佳答案

代码在测试数据上完全按照您所说的去做,提供 当然,值 (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();
}

打印出来:

19 91 83 41 74 12 11 

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

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}));
    }

}

关于java - 从 java 方法返回一个字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6137140/

相关文章:

java - 如何强制 hibernate 调用 setter 方法来填充类字段?

java - java中两个字符之间的分割

java - LocalDateTime 和数据库中的日期未舍入相同

java - 从服务更改另一个类中的 TextView

c++ - String Verifier 字符循环无法正常工作

java - 可变参数堆污染 : what's the big deal?

java - 创建String对象时创建了多少个对象

c- 使用结构指针将字符串扫描到结构中

c - 将 fgets() 与 char* 类型一起使用

java - 从一个字符串中提取两个子字符串