Java代码如何实现short数组和byte数组互转呢?
下文笔者讲述short数组和byte数组互相转换的方法分享,如下所示
short数组和byte数组互转的实现思路
由于一个byte占8位 一个short位占16位 所以转换时byte数组的两位放入short的一位,如下例所示例
byte数组转short数组
/**
* byte转short
* @param data
* @return
*/
public static short[] byteToShort(byte[] data) {
short[] shortValue = new short[data.length / 2];
for (int i = 0; i < shortValue.length; i++) {
shortValue[i] = (short) ((data[i * 2] & 0xff) | ((data[i * 2 + 1] & 0xff) << 8));
}
return shortValue;
}
short数组转byte数组
/**
* short转byte
* @param data
* @return
*/
public static byte[] shortToByte(short[] data) {
byte[] byteValue = new byte[data.length * 2];
for (int i = 0; i < data.length; i++) {
byteValue[i * 2] = (byte) (data[i] & 0xff);
byteValue[i * 2 + 1] = (byte) ((data[i] & 0xff00) >> 8);
}
return byteValue;
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


