今天一个小学弟问我位运算,我给他写了个东西,告诉他:把这个跑一遍就懂什么是位运算了。
/*
* 位运算
* */
public class IntToBinary {
public static void main(String[] args) throws UnsupportedEncodingException {
System.out.println("the 4 is : " + Integer.toBinaryString(4));
System.out.println("the 6 is : " + Integer.toBinaryString(6));
//位与&(真真为真 真假为假 假假为假)
System.out.println("the 4&6 is : " + Integer.toBinaryString(6&4));
//位或|(真真为真 真假为真 假假为假)
System.out.println("the 4|6 is : " + Integer.toBinaryString(6|4));
//位非~
System.out.println("the ~4 is : " + Integer.toBinaryString(~4));
//位异或^(真真为假 真假为真 假假为假)
System.out.println("the 4^6 is : " + Integer.toBinaryString(6^4));
//有符号右移>>(若正数,高位补0,负数,高位补1)
System.out.println("the 4>>1 is : " + Integer.toBinaryString(4>>1));
//有符号左移<<(若正数,低位补0,负数,低位补1)
System.out.println("the 4<<1 is : " + Integer.toBinaryString(4<<1));
//无符号右移>>>(不论正负,高位均补0)
System.out.println("the 234567 is : " + Integer.toBinaryString(234567));
System.out.println("the 234567>>>4 is : " + Integer.toBinaryString(234567>>>4));
//无符号右移>>>(不论正负,高位均补0)
System.out.println("the -4 is : " + Integer.toBinaryString(-4));
System.out.println("the -4>>>4 is : " + Integer.toBinaryString(-4>>>4));
System.out.println(Integer.parseInt(Integer.toBinaryString(-4>>>4), 2));
//取模a % (2^n) 等价于 a & (2^n - 1)
System.out.println("the 345 % 16 is : " + (345%16)+" or "+(345&(16-1)));
System.out.println("Mark hashCode is : "+"Mark".hashCode()+"="
+Integer.toBinaryString("Mark".hashCode()));
System.out.println("Bill hashCode is : "+"Bill".hashCode()+"="
+Integer.toBinaryString("Bill".hashCode()));
}
}
简单的小实例,权限控制
/**
* 位运算的运用-权限控制,add,query,modify,del
*/
public class Permission {
private static final int ALLOW_SELECT = 1<<0;
private static final int ALLOW_INSERT = 2<<1;
private static final int ALLOW_UPDATE = 1<<2;
private static final int ALLOW_DELETE = 1<<3;
//当前的权限状态
private int flag;
public void setPermission(int permission){
flag = permission;
}
/*增加权限,可以一项或者多项*/
public void addPermission(int permission){
flag = flag|permission;
}
/*删除权限,可以一项或者多项*/
public void disablePermission(int permission){
flag = flag&~permission;
}
/*是否拥有某些权限*/
public boolean isAllow(int permission){
return (flag&permission)==permission;
}
/*是否不拥有某些权限*/
public boolean isNotAllow(int permission){
return (flag&permission)==0;
}
public static void main(String[] args) {
int flag = 15;
Permission permission = new Permission();
permission.setPermission(flag);
permission.disablePermission(ALLOW_DELETE|ALLOW_INSERT);
System.out.println("ALLOW_DELETE|ALLOW_INSERT:"+(ALLOW_DELETE|ALLOW_INSERT));
System.out.println("ALLOW_SELECT="+permission.isAllow(ALLOW_SELECT));
System.out.println("ALLOW_INSERT="+permission.isAllow(ALLOW_INSERT));
System.out.println("ALLOW_UPDATE="+permission.isAllow(ALLOW_UPDATE));
System.out.println("ALLOW_DELETE="+permission.isAllow(ALLOW_DELETE));
System.out.println("ALLOW_SELECT:"+ALLOW_SELECT+","+"ALLOW_INSERT:"+ALLOW_INSERT+","+"ALLOW_UPDATE:"+ALLOW_UPDATE+","+"ALLOW_DELETE:"+ALLOW_DELETE);
}
}