字符串用gb2312编码:每个字符都要占2个字节,所以一个字符占16位。我这里的应用场景是具有顺序的土地的购买与否,就像开心农场的地块一样,不过我这里的地块是可以任意买下的(不用按顺序)。
假设有64块地,那么就需要64位来存储,就需要长度为4的字符串来实现。
我在看C++primer时突然看到有个bitset类,我就查了查java的果然也有一个。本来我实现位操作时到了符号位老出错,一直没解决,当时的思路也不是很好。
网络传输用字符串来传递,不过发get请求时应该用URLEncoder来对字符串encode一下。原因是get请求时空格什么的传输会造成错误。
{
BitSet bitSet = new BitSet(64);
boolean[] isMine = new boolean[]{true,true,false,false,true,false,true,true,true,false,false,false,true,false,true,true
,true,false,false,false,true,false,true,true,true,false,false,false,true,false,true,true
,true,false,false,false,true,false,true,true,true,false,false,false,true,false,true,true
,true,false,false,false,true,false,true,true,true,false,false,false,true,false,true,true};
bitSet.clear();
int len = isMine.length;
for(int i = 0;i < len;i++){
if(isMine[i] == true){
bitSet.set(i, true);
}
}
byte[] bytes = new byte[bitSet.length()/8];
for (int i=0; i<bitSet.length(); i++) {
if (bitSet.get(i)) {
bytes[bytes.length-i/8-1] |= 1<<(i%8);
}
}
String s = null;
try {
s = new String(bytes,"gb2312");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
byte[] bytess = null;
try {
bytess = s.getBytes("gb2312");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
BitSet bits = new BitSet(bytess.length*8);
for (int i=0; i<bytess.length*8; i++) {
if ((bytess[bytess.length-i/8-1]&(1<<(i%8))) > 0) {
bits.set(i);
}
}
int length = bits.length();
System.out.println(length);
for(int i = 0;i < length;i++){
if(bits.get(i) == true){
System.out.println(true);
}else{
System.out.println(false);
}
System.out.println(i);
}
}
一开始做移位时我移动的是被操作的byte,之后看了看别人移位的是 (byte)1。
现在的困惑 当我编码方式变为Unicode时得到的怎么是80位的结果,应该是64位才对啊?