LENGTH的数据格式如下表所示。
LENGTH共2个字节,由LENID和LCHKSUM组成,LENID表示INFO项的ASCII码字节数,当LENID=0时,INFO为空,即无该项。LENGTH传输中先传高字节,再传低字节,分四个ASCII码传送。
校验码的计算:D11D10D9D8+D7D6D5D4+D3D2D1D0,求和后模16的余数取反加1。
例如:
INFO项的ASCII码字节数为18,即LENID = 0000 0001 0010。
D11D10D9D8+D7D6D5D4+D3D2D1D0 = 0000 + 0001 + 0010 = 0011,模16余数为0011H,0011H取反加1(补码)就是1101H,即LCHKSUM为1101H。
可得:
LENGTH为 1101 0000 0001 0010,即D012H
public class LeetCode {
private final byte chkSum;
private final short lenId;
public LeetCode(short value) {
this.lenId = (short) (value & 0x0FFF);
this.chkSum = (byte) ((~((( (value >>> 8) & 0x0F) + ((value >>> 4) & 0x0F) + (value & 0x0F)) % 16) + 1) & 0x0F);
}
public byte getChkSum(){
return chkSum;
}
public short getLenId() {
return lenId;
}
public short getValue() {
return (short) (chkSum << 12 | lenId);
}
private String toBinaryString() {
return String.format("%04d %04d %04d %04d",
Integer.parseInt(Integer.toBinaryString(getChkSum())),
Integer.parseInt(Integer.toBinaryString(getLenId()>>>8)),
Integer.parseInt(Integer.toBinaryString((getLenId() >>> 4) & 0x0F)),
Integer.parseInt(Integer.toBinaryString(getLenId() & 0x0F)));
}
public String toHexString() {
return Integer.toHexString(getValue() & 0xFFFF);
}
@Override
public String toString() {
return toHexString().toUpperCase() + "H";
}
public static void main(String[] args) {
LeetCode leetCode = new LeetCode(Short.parseShort("000000010010", 2));
System.out.println(Integer.toBinaryString(leetCode.getChkSum()));
System.out.println(Integer.toBinaryString(leetCode.getLenId()));
System.out.println(leetCode.toBinaryString());
System.out.println(leetCode);
}
}