---
title: "全局唯一自增id生成"
author: "supben"
date: "2015-11-17T18:44:34Z"
tags: []
categories: ["移动开发"]
slug: "id"
draft: false
lastmod: "2015-11-25T14:43:30Z"
id: 2257422
url: "https://supben.iteye.com/blog/2257422"
---

```
public class Bbbb {
	public static void main(String[] args) {
		//42位时间戳+6位机器码+16位hash预留
		long time = System.currentTimeMillis();
		long serverid = 30; // serverid 不能超过64
		long userid = 123213123123l;
		long last16 = getLast(userid, 16);
		System.out.println(last16);
		
		long id = (time << 22) + (serverid << 16) + last16;
		System.out.println(id);
		
		long id_last16 = getLast(id, 16);
		System.out.println(id_last16);
	}
	
	public static long getLast(long l, int last){
		long i =  (l >> last) << last;
		return l-i;
	}
}
```