用位来保存信息

字符串用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位才对啊?

转载于:https://www.cnblogs.com/wendao/archive/2011/07/07/2609150.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值