java實現(xiàn)無符號數(shù)轉(zhuǎn)換、字符串補齊、md5、uuid、隨機數(shù)示例

package com.hongyuan.test;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import java.util.UUID;
/*
* 雜項(無符號數(shù)轉(zhuǎn)換,字符串補齊,md5,uuid,隨機數(shù))
*/
public class SundryTest {
//轉(zhuǎn)成無符號數(shù)
public static Number toUnsignedNumber(Number num){
if(num instanceof Byte){
return (Byte)num & 0xff;
}else if(num instanceof Short){
return (Short)num & 0xffff;
}else if(num instanceof Integer){
return (Integer)num & 0xffffffffL;
}else{
return -1;
}
}
//左補齊
public static String leftPad(String str,String pad,int len){
String newStr=(str==null?"":str);
while(newStr.length()<len){
newStr=pad+newStr;
}
if(newStr.length()>len){
newStr=newStr.substring(newStr.length()-len);
}
return newStr;
}
//右補齊
public static String rightPad(String str,String pad,int len){
String newStr=(str==null?"":str);
while(newStr.length()<len){
newStr=newStr+pad;
}
if(newStr.length()>len){
newStr=newStr.substring(0, len);
}
return newStr;
}
//md5
public static String md5(String str){
StringBuilder sb=new StringBuilder();
try {
MessageDigest digest = MessageDigest.getInstance("MD5");
byte[] message=digest.digest(str.getBytes());
for(int i=0;i<message.length;i++){
sb.append(leftPad( //左補齊
Integer.toHexString( //轉(zhuǎn)成16進制數(shù)
(Integer)toUnsignedNumber(message[i])), //轉(zhuǎn)成無符號數(shù)
"0",2).toUpperCase()); //轉(zhuǎn)成大寫
}
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("不存在md5服務(wù)!");
}
return sb.toString();
}
//UUID
public static String uuid(){
return UUID.randomUUID().toString().replaceAll("-","").toUpperCase();
}
//隨機數(shù)(包括min,不包括max)
public static int random(int min,int max){
if(min<=max){
Random random=new Random();
return random.nextInt(max-min)+min;
}else{
throw new IllegalArgumentException("無法處理一個不合法的數(shù)字區(qū)間!");
}
}
public static void main(String[] args){
System.out.println("MD5(123456):"+md5("123456"));
System.out.println("UUID:"+uuid());
System.out.println("隨機數(shù):"+random(1,100));
}
}
相關(guān)文章
新建springboot項目時,entityManagerFactory報錯的解決
這篇文章主要介紹了新建springboot項目時,entityManagerFactory報錯的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-01-01
IDEA 2020.1 for Mac 下載安裝配置及出現(xiàn)的問題小結(jié)
這篇文章主要介紹了IDEA 2020.1 for Mac 下載安裝配置及出現(xiàn)的問題小結(jié),本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03
SpringBoot+MinIO實現(xiàn)文件切片極速詳解
在現(xiàn)代Web應(yīng)用中,文件上傳是一個常見的需求,尤其是對于大文件的上傳,如視頻、音頻或大型文檔,所以本文就來為大家介紹一下如何使用Spring Boot和MinIO實現(xiàn)文件切片極速上傳技術(shù)吧2023-12-12

