接口1:byte数组转short数组

public interface ByteToShortConverter {
    short[] convert(byte[] byteArray);
}

接口2:short数组转byte数组

public interface ShortToByteConverter {
    byte[] convert(short[] shortArray);
}

使用示例:

public class Main {
    public static void main(String[] args) {
        ByteToShortConverter byteToShortConverter = new ByteToShortConverterImpl();
        ShortToByteConverter shortToByteConverter = new ShortToByteConverterImpl();

        byte[] byteArray = {1, 2, 3, 4};
        short[] shortArray = byteToShortConverter.convert(byteArray);
        System.out.println(Arrays.toString(shortArray)); // [258, 772]

        byte[] convertedByteArray = shortToByteConverter.convert(shortArray);
        System.out.println(Arrays.toString(convertedByteArray)); // [1, 0, 2, 0]
    }
}

实现示例1:byte数组转short数组

public class ByteToShortConverterImpl implements ByteToShortConverter {
    @Override
    public short[] convert(byte[] byteArray) {
        int length = byteArray.length / 2;
        short[] shortArray = new short[length];

        for (int i = 0; i < length; i++) {
            shortArray[i] = (short) (((byteArray[i * 2] & 0xFF) << 8) | (byteArray[i * 2 + 1] & 0xFF));
        }

        return shortArray;
    }
}

实现示例2:short数组转byte数组

public class ShortToByteConverterImpl implements ShortToByteConverter {
    @Override
    public byte[] convert(short[] shortArray) {
        int length = shortArray.length * 2;
        byte[] byteArray = new byte[length];

        for (int i = 0; i < shortArray.length; i++) {
            byteArray[i * 2] = (byte) (shortArray[i] >> 8);
            byteArray[i * 2 + 1] = (byte) shortArray[i];
        }

        return byteArray;
    }
}
``
android开发: 给我两个接口byte数组转short数组、short数组转byte数组

原文地址: https://www.cveoy.top/t/topic/iHxE 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录