kotlin&java - byte 数组转 int 数据,有符号和无符号转换类

在做 android 与蓝牙上的加速度传感器通信时,通信规格为 每个 x,y,z 值均占2个字节,即2个byte数据;

先温习下 kotlin 上的移位运算:

shl(bits) – 左移位 (Java’s <<)
shr(bits) – 右移位 (Java’s >>)
ushr(bits) – 无符号右移位 (Java’s >>>)
and(bits) – 与
or(bits) – 或
xor(bits) – 异或
inv() – 反向

Java 版数据解析

public class DataParseUtil {


    /**
     * 有符号,int 占 2 个字节
     */
    public static int convertTwoSignInt(byte b1, byte b2) { // signed
        return (b2 << 8) | (b1 & 0xFF);
    }

    /**
     * 有符号, int 占 4 个字节
     */
    public static int convertFourSignInt(byte b1, byte b2, byte b3, byte b4) {
        return (b4 << 24) | (b3 & 0xFF) << 16 | (b2 & 0xFF) << 8 | (b1 & 0xFF);
    }

    /**
     * 无符号,int 占 2 个字节
     */
    public static int convertTwoUnsignInt(byte b1, byte b2)      // unsigned
    {
        return (b2 & 0xFF) << 8 | (b1 & 0xFF);
    }

    /**
     * 无符号, int 占 4 个字节
     */
    public static long convertFoutUnsignLong(byte b1, byte b2, byte b3, byte b4) {
        return (long) (b4 & 0xFF) << 24 | (b3 & 0xFF) << 16 | (b2 & 0xFF) << 8 | (b1 & 0xFF);
    }
}

Kotlin 数据解析

class KUtil {
    // 有符号
    fun convertTwoSignInt(byteArray: ByteArray): Int =
            (byteArray[1].toInt() shl 8) or (byteArray[0].toInt() and 0xFF)

    fun convertTwoUnSignInt(byteArray: ByteArray): Int =
            (byteArray[3].toInt() shl 24) or (byteArray[2].toInt() and 0xFF) or (byteArray[1].toInt() shl 8) or (byteArray[0].toInt() and 0xFF)

    // 无符号
    fun convertFourUnSignInt(byteArray: ByteArray): Int =
            (byteArray[1].toInt() and 0xFF) shl 8 or (byteArray[0].toInt() and 0xFF)

    fun convertFourUnSignLong(byteArray: ByteArray): Long =
            ((byteArray[3].toInt() and 0xFF) shl 24 or (byteArray[2].toInt() and 0xFF) shl 16 or (byteArray[1].toInt() and 0xFF) shl 8 or (byteArray[0].toInt() and 0xFF)).toLong()

}

你可能感兴趣的:(kotlin)