我有class元素,它有以下属性(参见class)。由于这两个整数值的范围非常小,所以我想把它们存储在一个短的地方。这对我不起作用。我想使用位移位。我在这里做错了什么?这是学校的作业,所以一定是短篇。
public class Element implements Externalizable {
private static final long serialVersionUID = 6529685098267757690L;
private boolean isMarked;
private boolean isValid;
private boolean isDeleted;
private int key; // VALUE AREA: 0-500
private int value; // VALUE AREA: 1-10
@Override
public void writeExternal(ObjectOutput out) throws IOException {
short val =0;
if(this.isMarked) val|=1;
val <<=1;
if(this.isValid) val|=1;
val <<=1;
if(this.isDeleted) val|=1;
val <<=4;
val |= this.value;
val <<=9;
val |= (short) this.key;
out.writeShort(val);
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
short s = in.readShort();
this.isMarked = s % 2==1;
s >>= 1;
this.isValid =s % 2==1;
s >>>= 1;
this.isDeleted = s % 2==1;
s >>>= 4;
this.value = s % 8;
s >>>=9;
this.value = s % 512;
}
@Override
public String toString() {
return "Element{" +
"isMarked=" + isMarked +
", isValid=" + isValid +
", isDeleted=" + isDeleted +
", key=" + key +
", value=" + value +
'}';
}
public Element(boolean isMarked, boolean isValid, boolean isDeleted, int key, int value) {
this.isMarked = isMarked;
this.isValid = isValid;
this.isDeleted = isDeleted;
this.key = key;
this.value = value;
}
public Element(){}
}发布于 2021-06-30 15:50:12
以相反的顺序读取数据。使用二元and运算符而不是模运算符,因为short是有符号的。然后负数会导致您的评论中描述的问题。
将readExternal更改为:
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
short s = in.readShort();
this.key = s & 511; // masks the lower 9 bits
s >>>= 9;
this.value = s & 15; // masks the lower 4 bits
s >>>= 4;
this.isDeleted = (s & 1) == 1;
s >>>= 1;
this.isValid = (s & 1) == 1;
s >>>= 1;
this.isMarked = (s & 1) == 1;
}https://stackoverflow.com/questions/68184899
复制相似问题