通过位运算生成ID

public static void main(String[] args) {
        long serverId = 65535;
        System.out.println("ServerId:" + serverId);
        long a1 = 0b11110001001000000;// 123456
        // 11110001001000000
        // 0000000000000000
        System.out.println("顺序号,a1:" + a1);
        long a2 = a1 << 16;
        System.out.println("左移16位,a2:" + a2);
        // 11110001001000000 0000000000000000 //8090812416
        // 00000000000000000 1111111111111111 //65535
        // 11110001001000000 1111111111111111 //8090877951
        long a3 = a2 | serverId;// 加入ServerId
        System.out.println("加入ServerId,a3:" + a3);

        long a4 = a3 >> 16;
        System.out.println("还原顺序号,a4:" + a4);
        // 11110001001000000 1111111111111111 //8090877951
        // 00000000000000001 1110001001000000 //123456

        long a5 = a3 & 65535;
        System.out.println("还原ServerId,a5:" + a5);
        // 11110001001000000 1111111111111111 //8090877951
        // 00000000000000000 1111111111111111 //65535 
        // 两个位都为1时输出1,否则0
        // 00000000000000000 1111111111111111 //65535
    }

 

输出结果:

ServerId:65535
顺序号,a1:123456
左移16位,a2:8090812416
加入ServerId,a3:8090877951
还原顺序号,a4:123456
还原ServerId,a5:65535

 

你可能感兴趣的:(位运算)