前言
最近在工作中,遇到一个需要通过 byte[]
类型发送控制指令的需求
过程分析
此次用到了两个简易的位运算和一个小常识
-
按位与(&):两个操作数按位进行与运算
-
按位或(|):两个操作数按位进行或运算
-
按位与(&)1 数据保持不变,按位或(|)0 数据将强制变为 0
结论
通过约定,首位作为是否切换的布尔值,其余位作为附加数据,可以在一个字节内编码一些简单的配置项信息
import java.util.Arrays;
public class Command {
private boolean mSwitchCamera;
private byte mSwitchCameraId;
private boolean mSwitchQuality;
private byte mSwitchQualityId;
private Command() {
}
public Command(boolean mSwitchCamera, byte mSwitchCameraId, boolean mSwitchQuality, byte mSwitchQualityId) {
this.mSwitchCamera = mSwitchCamera;
this.mSwitchCameraId = mSwitchCameraId;
this.mSwitchQuality = mSwitchQuality;
this.mSwitchQualityId = mSwitchQualityId;
}
public static Command parse(byte[] dataArray) {
Command command = null;
if (dataArray != null && dataArray.length > 0) {
command = new Command();
command.mSwitchCamera = (dataArray[0] & -128) == -128;
command.mSwitchCameraId = (byte) (dataArray[0] & 127);
command.mSwitchQuality = (dataArray[1] & -128) == -128;
command.mSwitchQualityId = (byte) (dataArray[1] & 127);
}
return command;
}
public static byte[] compact(Command command) {
byte[] data = null;
if (command != null) {
data = new byte[2];
data[0] = (byte) (command.mSwitchCameraId & 127);
if (command.mSwitchCamera) {
data[0] |= -128;
}
data[1] = (byte) (command.mSwitchQualityId & 127);
if (command.mSwitchQuality) {
data[1] |= -128;
}
}
return data;
}
public boolean isSwitchCamera() {
return mSwitchCamera;
}
public byte getSwitchCameraId() {
return mSwitchCameraId;
}
public boolean isSwitchQuality() {
return mSwitchQuality;
}
public byte getSwitchQualityId() {
return mSwitchQualityId;
}
@Override
public String toString() {
return "Command{" + "mSwitchCamera=" + mSwitchCamera + ", mSwitchCameraId=" + mSwitchCameraId + ", mSwitchQuality=" + mSwitchQuality + ", mSwitchQualityId=" + mSwitchQualityId + '}';
}
public static void main(String[] args) {
Command command = new Command(true, (byte) 3, false, (byte) 66);
byte[] data = compact(command);
System.out.println(Arrays.toString(data));
System.out.println(parse(data));
}
}
标签:编码,逻辑,mSwitchCameraId,简陋,command,Command,byte,data,public
From: https://www.cnblogs.com/slkagura/p/16859446.html