java實現(xiàn)無符號數(shù)轉換、字符串補齊、md5、uuid、隨機數(shù)示例
package com.hongyuan.test;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import java.util.UUID;
/*
* 雜項(無符號數(shù)轉換,字符串補齊,md5,uuid,隨機數(shù))
*/
public class SundryTest {
//轉成無符號數(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( //轉成16進制數(shù)
(Integer)toUnsignedNumber(message[i])), //轉成無符號數(shù)
"0",2).toUpperCase()); //轉成大寫
}
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("不存在md5服務!");
}
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));
}
}
相關文章
springboot控制層傳遞參數(shù)為非必填值的操作
這篇文章主要介紹了springboot控制層傳遞參數(shù)為非必填值的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10Java自動化測試中多數(shù)據(jù)源的切換(實例講解)
下面小編就為大家?guī)硪黄狫ava自動化測試中多數(shù)據(jù)源的切換(實例講解)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-10-10Springboot使用異步請求提高系統(tǒng)的吞吐量詳解
這篇文章主要介紹了Springboot使用異步請求提高系統(tǒng)的吞吐量詳解,和同步請求相對,異步不需要等待響應,隨時可以發(fā)送下一次請求,如果是同步請求,需要將信息填寫完整,再發(fā)送請求,服務器響應填寫是否正確,再做修改,需要的朋友可以參考下2023-08-08