java程序员必备的并发编程基础知识( hash以及位运算)

30 篇文章 1 订阅
9 篇文章 1 订阅

Hash

散列,哈希:把任意长度的输入通过一种算法(散列),变换成为固定长度的输出,这个输出值就是散列值。属于压缩映射,容易产生哈希冲突。Hash算法有直接取余法等。

产生哈希冲突时解决办法:开放寻址;2、再散列;3、链地址法(相同hash值的元素用链表串起来)。

ConcurrentHashMap在发生hash冲突时采用了链地址法。

md4,md5,sha-hash算法也属于hash算法,又称摘要算法。

位运算

int类型的位

高位                                                                                                                               低位

31

30

29

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

5

4

3

2

1

0

0

0

0

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

1

0

1

0

0

0

2的0次方 = 1,2的1次方=2…….,以上表格代表数字 (2的5次方+2的3次方)= 40

由上面的表格可以看出,数字类型在数字渐渐变大时,是由低位慢慢向高位扩展的。

Java实际保存int型时 正数  第31位 =0 负数:第31位=1

常用位运算有:

  1. 位与  &  (1&1=1 1&0=0  0&0=0)
  2. 位或  |   (1|1=1  1|0=1 0|0=0)
  3. 位非  ~  ( ~1=0  ~0=1)

  4. 位异或  ^   (1^1=0  1^0=1  0^0=0)

  5. <<有符号左移     >>有符号的右移    >>>无符号右移  例如:8 << 2 = 32 8>>2 = 2

       >>表示右移,如果该数为正,则高位补0,若为负数,则高位补1;

       >>>表示无符号右移,也叫逻辑右移,即若该数为正,则高位补0,而若该数为负数,则右移后高位同样补0。

       左移没有<<<运算符!

 

     取模的操作 a % (Math.pow(2,n)) 等价于 a&( Math.pow(2,n)-1),一个数字取模于2的n次方=a&2的n次方-1

 

代码实现:

package com.caojiulu;

import java.io.UnsupportedEncodingException;
/**
 *@author caojiulu
 *
 *类说明:演示位运算
 */
public class IntToBinary {
	
    public static void main(String[] args) throws UnsupportedEncodingException {
    	
    	int data = 4;
    	System.out.println("the 4 is "+Integer.toBinaryString(data));
    	
    	//位与  &(1&1=1 1&0=0 0&0=0)
    	System.out.println("the 4 is "+Integer.toBinaryString(4));
    	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(4&6));
    	//位或 | (1|1=1 1|0=1 0|0=0)
    	System.out.println("the 4|6 is "+Integer.toBinaryString(4|6));
    	//位非~(~1=0  ~0=1)
    	System.out.println("the ~4 is "+Integer.toBinaryString(~4));
    	//位异或 ^ (1^1=0 1^0=1 0^0=0)
    	System.out.println("the 4^6 is "+Integer.toBinaryString(4^6));
    	
    	// <<有符号左移 >>有符号的右移  >>>无符号右移
    	System.out.println("the -4 is >>>"+Integer.toBinaryString(-4>>>8));
    	// <<有符号左移 >>有符号的右移  >>>无符号右移
    	System.out.println("the -4 is >>"+Integer.toBinaryString(-4>>8));
    	//取模的操作 a % (2^n) 等价于 a&(2^n-1)
    	System.out.println("the 345 % 16 is "+(345%16)+ " or "+(345&(16-1)));
    	
    } 
}

运行结果:

the 4 is 100
the 4 is 100
the -4 is 11111111111111111111111111111100
the 6 is 110
the 4&6 is 100
the 4|6 is 110
the ~4 is 11111111111111111111111111111011
the 4^6 is 10
the -4 is >>>111111111111111111111111
the -4 is >>11111111111111111111111111111111
the 345 % 16 is 9 or 9
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值