Kotlin中可以使用位运算符来设置byte八个位的值,具体如下:
fun Byte.withBit(index: Int, bit: Int): Byte { return if (bit == 0) this and (1 shl index).inv().toByte() else this or (1 shl index).toByte() }
val flag1: Int = 1 //0主机 //1终端从机 val flag2: Int = 0 //回复标志 0发起指令 //1 回复指令 val flag3: Int = 0 //包标志位 0表示只有一包 1表示有多包 val flag4: Int = 0 //成功标志位 0 成功 1失败 val flag5: Int = 0 //预留 val flag6: Int = 0 //预留 val flag7: Int = 0 //预留 val flag8: Int = 0 //预留 var flag:Byte = 0 flag = flag.withBit(0,flag1) flag = flag.withBit(1,flag2) flag = flag.withBit(2,flag3) flag = flag.withBit(3,flag4) flag = flag.withBit(4,flag5) flag = flag.withBit(5,flag6) flag = flag.withBit(6,flag7) flag = flag.withBit(7,flag8)