中央热水项目
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1238 lines
38 KiB

package com.mh.user.utils;
import com.mh.common.utils.StringUtils;
//import io.netty.buffer.ByteBuf;
//import io.netty.channel.ChannelHandlerContext;
import java.io.*;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @Auther: LJF
* @Date: 2020-02-26 15:11
* @Description:
*/
public class ExchangeStringUtil {
public static void main(String args[]){
String s = floatToHex(12555.45F);
System.out.println(s);
System.out.println(hexToLong("0000006C"));
System.out.println(longToHex(317751L));
}
/**
* 长整型转16进制
* @param value
* @return
*/
public static String longToHex(long value) {
String hexString = Long.toHexString(value);
while (hexString.length() < 8) {
hexString = "0" + hexString;
}
return hexString;
}
/**
* 16进制转长整型
* @param hexString
* @return
*/
public static long hexToLong(String hexString) {
return Long.parseLong(hexString, 16); // 将16进制字符串解析为长整型
}
//十六进制转正负数十进制
public static double parseHex4(String num) {
if (num.length() != 4) {
throw new NumberFormatException("Wrong length: " + num.length() + ", must be 4.");
}
int ret = Integer.parseInt(num, 16);
ret = ((ret & 0x8000) > 0) ? (ret - 0x10000) : (ret);
return (double) ret;
}
//十六进制转十进制
public static int covert(String content){
int number=0;
String [] HighLetter = {"A","B","C","D","E","F"};
Map<String,Integer> map = new HashMap<>();
for(int i = 0;i <= 9;i++){
map.put(i+"",i);
}
for(int j= 10;j<HighLetter.length+10;j++){
map.put(HighLetter[j-10],j);
}
String[]str = new String[content.length()];
for(int i = 0; i < str.length; i++){
str[i] = content.substring(i,i+1);
}
for(int i = 0; i < str.length; i++){
number += map.get(str[i])*Math.pow(16,str.length-1-i);
}
return number;
}
public static int hexToDecimal(String hex){
int outcome = 0;
for(int i = 0; i < hex.length(); i++){
char hexChar = hex.charAt(i);
outcome = outcome * 16 + charToDecimal(hexChar);
}
return outcome;
}
public static int charToDecimal(char c){
if(c >= 'A' && c <= 'F')
return 10 + c - 'A';
else
return c - '0';
}
// /**
// * 获取到对应的buffer
// * @param ctx
// * @param sendStr
// * @return
// */
// public static ByteBuf getByteBuf(ChannelHandlerContext ctx, String sendStr) {
// // byte类型的数据
//// byte[] bytes = "这里是将要写往服务端的数据".getBytes(Charset.forName("utf-8"));
//// String sendStr = "5803004900021914"; // 冷量计
// // 申请一个数据结构存储信息
// ByteBuf buffer = ctx.alloc().buffer();
// // 将信息放入数据结构中
// buffer.writeBytes(ExchangeStringUtil.hexStrToBinaryStr(sendStr));//对接需要16进制
// return buffer;
// }
/**
* double转换为String :当为整数时,只显示整数,当小数时直接显示小数
* @param num
* @return
*/
public static String doubleTrans1(double num){
if(num % 1.0 == 0){
return String.valueOf((long)num);
}
return String.valueOf(num);
}
/**
* 获取String中的数值
* @param result
* @return
*/
public static String getNumFromString(String result) {
String regEx="[^0-9]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(result);
return m.replaceAll("").trim();
}
/**
* 获取检验位值,update by ljf on 2020-06-02
* @param result
* @return
*/
//返回指令+校验码
public static String getCRCStr(String result) {
byte[] strOrder = ExchangeStringUtil.hexStrToBinaryStr(result);
int checkNum = CRC16.CRC16_MODBUS(strOrder);
String checkWord = ExchangeStringUtil.decToHex(String.valueOf(checkNum));
checkWord = ExchangeStringUtil.addZeroForNum(checkWord,4);
checkWord = checkWord.substring(2,4) + checkWord.substring(0,2);
result = result + checkWord;
return result;
}
//只返回校验码
public static String getStrCRC16(String result) {
byte[] strOrder = ExchangeStringUtil.hexStrToBinaryStr(result);
int checkNum = CRC16.CRC16_MODBUS(strOrder);
String checkWord = ExchangeStringUtil.decToHex(String.valueOf(checkNum));
checkWord = ExchangeStringUtil.addZeroForNum(checkWord,4);
checkWord = checkWord.substring(2,4) + checkWord.substring(0,2);
return checkWord;
}
public static String getMidString(String str, String beginStr, String endStr) {
String regex = beginStr + "(.*)" + endStr;
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
String result = "";
while (matcher.find()) {
result = matcher.group(1);
}
return result;
}
/**
* 字符串不足补“0”
* @param str
* @param strLength
* @return
*/
public static String addZeroForNum(String str, int strLength) {
int strLen = str.length();
if (strLen < strLength) {
while (strLen < strLength) {
StringBuffer sb = new StringBuffer();
sb.append("0").append(str);// 左补0
// sb.append(str).append("0");//右补0
str = sb.toString();
strLen = str.length();
}
}
return str;
}
/**
* ip地址转换成16进制long
* @param ipString
* @return
*/
public static String ipToHex(String ipString) {
String[] strings = ipString.split("\\.");
String result = "";
for (int i = 0; i < strings.length; i++) {
result = result + ExchangeStringUtil.decToHex(strings[i]);
}
return result;
}
/**
* ip地址转换成16进制long
* @param ipString
* @return
*/
public static Long ipToLong(String ipString) {
Long[] ip = new Long[4];
int pos1= ipString.indexOf(".");
int pos2= ipString.indexOf(".",pos1+1);
int pos3= ipString.indexOf(".",pos2+1);
ip[0] = Long.parseLong(ipString.substring(0 , pos1));
ip[1] = Long.parseLong(ipString.substring(pos1+1 , pos2));
ip[2] = Long.parseLong(ipString.substring(pos2+1 , pos3));
ip[3] = Long.parseLong(ipString.substring(pos3+1));
return (ip[0]<<24)+(ip[1]<<16)+(ip[2]<<8)+ip[3];
}
public static String splitData(String str, String strStart, String strEnd) {
String tempStr;
tempStr = str.substring(str.indexOf(strStart) + 1, str.lastIndexOf(strEnd));
return tempStr;
}
public static String endData(String str, String strStart) {
String tempStr;
String str1=str.substring(0, str.indexOf(strStart));
tempStr=str.substring(str1.length()+1);
return tempStr;
}
// 转换位置
public static String changePosition(String changeStr) {
StringBuffer s1 = new StringBuffer();
for (int i = changeStr.length(); i >= 2; i = i - 2) {
s1 = s1.append(changeStr.substring(i - 2, i));
}
return s1.toString();
}
// 加33
public static String addThree(String data){
String result = "";
for (int i = 0; i < data.length() / 2; i++) {
BigInteger a = new BigInteger(data.substring(2*i,2*(i+1)),16);
BigInteger b = new BigInteger("33",16);
BigInteger c = a.add(b);
result = result + ExchangeStringUtil.decToHex(c.toString(10));
}
return result;
}
// 减33
public static String cutThree(String data){
String result = "";
for (int i = 0; i < data.length() / 2; i++) {
BigInteger a = new BigInteger(data.substring(2*i,2*(i+1)),16);
BigInteger b = new BigInteger("33",16);
BigInteger c = a.subtract(b);
result = result + ExchangeStringUtil.decToHex(c.toString(10));
}
return result;
}
public static String makeChecksum(String data) {
if (data == null || data.equals("")) {
return "";
}
int total = 0;
int len = data.length();
int num = 0;
while (num < len) {
String s = data.substring(num, num + 2);
total += Integer.parseInt(s, 16);
num = num + 2;
}
/**
* 用256求余最大是255,即16进制的FF
*/
int mod = total % 256;
String hex = Integer.toHexString(mod);
len = hex.length();
// 如果不够校验位的长度,补0,这里用的是两位校验
if (len < 2) {
hex = "0" + hex;
}
return hex;
}
/**
* 十进制数据转换为十六进制字符串数
*
* @param dec
* @return
*/
public static String decToHex(String dec) {
BigInteger data = new BigInteger(dec,10);
String result = data.toString(16);
if (result.length() < 2) {
result = "0" + result;
}
if ((result.length() % 2)!=0) {
result = "0" + result;
}
return result.toUpperCase();
}
/**
* 十六进制数据转换为十进制字符串数
*
* @param hex
* @return
*/
public static String hexToDec(String hex) {
BigInteger data = new BigInteger(hex,16);
return data.toString(10);
}
public static String IntToHex(int n){
char[] ch = new char[20];
int nIndex = 0;
while ( true ){
int m = n/16;
int k = n%16;
if ( k == 15 )
ch[nIndex] = 'F';
else if ( k == 14 )
ch[nIndex] = 'E';
else if ( k == 13 )
ch[nIndex] = 'D';
else if ( k == 12 )
ch[nIndex] = 'C';
else if ( k == 11 )
ch[nIndex] = 'B';
else if ( k == 10 )
ch[nIndex] = 'A';
else
ch[nIndex] = (char)('0' + k);
nIndex++;
if ( m == 0 )
break;
n = m;
}
StringBuffer sb = new StringBuffer();
sb.append(ch, 0, nIndex);
sb.reverse();
String strHex = new String("");
strHex += sb.toString();
return strHex;
}
// 字节数组转字符串
public static String printHexString(byte[] b) {
StringBuffer sbf = new StringBuffer();
for (int i = 0; i < b.length; i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sbf.append(hex.toUpperCase() + " ");
}
return sbf.toString().trim();
}
public static String bytesToHexString(byte[] src){
StringBuilder stringBuilder = new StringBuilder("");
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
/**
* 字符串转化成为16进制字符串
* @param s
* @return
*/
public static String strTo16(String s) {
String str = "";
for (int i = 0; i < s.length(); i++) {
int ch = (int) s.charAt(i);
String s4 = Integer.toHexString(ch);
str = str + s4;
}
return str;
}
/**
* 字符串转换成为16进制(无需Unicode编码)
* @param str
* @return
*/
public static String str2HexStr(String str) {
char[] chars = "0123456789ABCDEF".toCharArray();
StringBuilder sb = new StringBuilder("");
byte[] bs = str.getBytes();
int bit;
for (int i = 0; i < bs.length; i++) {
bit = (bs[i] & 0x0f0) >> 4;
sb.append(chars[bit]);
bit = bs[i] & 0x0f;
sb.append(chars[bit]);
// sb.append(' ');
}
return sb.toString().trim();
}
/**
* 16进制转换成为string类型字符串
* @param s
* @return
*/
public static String hexStringToString(String s) {
if (s == null || s.equals("")) {
return null;
}
s = s.replace(" ", "");
byte[] baKeyword = new byte[s.length() / 2];
for (int i = 0; i < baKeyword.length; i++) {
try {
baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
} catch (Exception e) {
e.printStackTrace();
}
}
try {
s = new String(baKeyword, "UTF-8");
new String();
} catch (Exception e1) {
e1.printStackTrace();
}
return s;
}
/**
* 字节转十六进制
* @param b 需要进行转换的byte字节
* @return 转换后的Hex字符串
*/
public static String byteToHex(byte b){
String hex = Integer.toHexString(b & 0xFF);
if(hex.length() < 2){
hex = "0" + hex;
}
return hex;
}
/**
* hex字符串转byte数组
* @param inHex 待转换的Hex字符串
* @return 转换后的byte数组结果
*/
public static byte[] hexToByteArray(String inHex){
int hexlen = inHex.length();
byte[] result;
if (hexlen % 2 == 1){
//奇数
hexlen++;
result = new byte[(hexlen/2)];
inHex="0"+inHex;
}else {
//偶数
result = new byte[(hexlen/2)];
}
int j=0;
for (int i = 0; i < hexlen; i+=2){
result[j]=(byte)Integer.parseInt(inHex.substring(i,i+2),16);
j++;
}
return result;
}
/**
* 将十六进制的字符串转换成字节数组
*
* @param hexString
* @return
*/
public static byte[] hexStrToBinaryStr(String hexString) {
hexString = hexString.replaceAll(" ", "");
int len = hexString.length();
int index = 0;
byte[] bytes = new byte[len / 2];
while (index < len) {
String sub = hexString.substring(index, index + 2);
bytes[index/2] = (byte) Integer.parseInt(sub,16);
index += 2;
}
return bytes;
}
/**
* 获取当前日期 : "yyyy-MM-dd HH:mm:ss"
*
* @return "yyyy-MM-dd HH:mm:ss"字符串
*/
public static String formatDateStr_ss() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
}
/**
* 字符串是否为空
* 如果这个字符串为null或者trim后为空字符串则返回true,否则返回false。
* @param str
* @return
*/
public static boolean isEmpty(String str) {
if (str == null || "".equals(str.trim()))
return true;
return false;
}
/**
* 用来把mac字符串转换为long
* @param strMac
* @return
*/
public static long macToLong(String strMac) {
byte[] mb = new BigInteger(strMac, 16).toByteArray();
ByteBuffer mD = ByteBuffer.allocate(mb.length);
mD.put(mb);
long mac = 0;
// 如果长度等于8代表没有补0;
if (mD.array().length == 8) {
mac = mD.getLong(0);
} else if (mD.array().length == 9) {
mac = mD.getLong(1);
}
return mac;
}
public static byte[] getBytes(Object obj) throws IOException {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bout);
out.writeObject(obj);
out.flush();
byte[] bytes = bout.toByteArray();
bout.close();
out.close();
return bytes;
}
public static Object getObject(byte[] bytes) throws IOException, ClassNotFoundException {
ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
ObjectInputStream oi = new ObjectInputStream(bi);
Object obj = oi.readObject();
bi.close();
oi.close();
return obj;
}
public static ByteBuffer getByteBuffer(Object obj) throws IOException {
byte[] bytes = ExchangeStringUtil.getBytes(obj);
ByteBuffer buff = ByteBuffer.wrap(bytes);
return buff;
}
/**
* byte[] 转short 2字节
* @param bytes
* @return
*/
public static short bytesToshort(byte[] bytes) {
return (short) ((bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00));
}
/**
* byte 转Int
* @param b
* @return
*/
public static int byteToInt(byte b) {
return (b) & 0xff;
}
public static int bytesToInt(byte[] bytes) {
int addr = bytes[0] & 0xFF;
addr |= ((bytes[1] << 8) & 0xFF00);
addr |= ((bytes[2] << 16) & 0xFF0000);
addr |= ((bytes[3] << 24) & 0xFF000000);
return addr;
}
public static byte[] intToByte(int i) {
byte[] abyte0 = new byte[4];
abyte0[0] = (byte) (0xff & i);
abyte0[1] = (byte) ((0xff00 & i) >> 8);
abyte0[2] = (byte) ((0xff0000 & i) >> 16);
abyte0[3] = (byte) ((0xff000000 & i) >> 24);
return abyte0;
}
public static byte[] LongToByte(Long i) {
byte[] abyte0 = new byte[8];
abyte0[0] = (byte) (0xff & i);
abyte0[1] = (byte) ((0xff00 & i) >> 8);
abyte0[2] = (byte) ((0xff0000 & i) >> 16);
abyte0[3] = (byte) ((0xff000000 & i) >> 24);
abyte0[4] = (byte) ((0xff00000000l & i) >> 32);
abyte0[5] = (byte) ((0xff0000000000l & i) >> 40);
abyte0[6] = (byte) ((0xff000000000000l & i) >> 48);
abyte0[7] = (byte) ((0xff00000000000000l & i) >> 56);
return abyte0;
}
/**
* 函数名称:shortChange</br>
* 功能描述:short 大端转小端
* @param mshort
*/
public static short shortChange(Short mshort) {
mshort = (short) ((mshort >> 8 & 0xFF) | (mshort << 8 & 0xFF00));
return mshort;
}
/**
* 函数名称:intChange</br>
* 功能描述:int 大端转小端
* @param mint
*/
public static int intChange(int mint) {
mint = (int) (((mint) >> 24 & 0xFF) | ((mint) >> 8 & 0xFF00) | ((mint) << 8 & 0xFF0000)
| ((mint) << 24 & 0xFF000000));
return mint;
}
/**
* 函数名称:intChange</br>
* 功能描述:LONG 大端转小端
* @param mlong
*/
public static long longChange(long mlong) {
mlong = (long) (((mlong) >> 56 & 0xFF) | ((mlong) >> 48 & 0xFF00) | ((mlong) >> 24 & 0xFF0000)
| ((mlong) >> 8 & 0xFF000000) | ((mlong) << 8 & 0xFF00000000l) | ((mlong) << 24 & 0xFF0000000000l)
| ((mlong) << 40 & 0xFF000000000000l) | ((mlong) << 56 & 0xFF00000000000000l));
return mlong;
}
/**
* 将byte转换为无符号的short类型
* @param b 需要转换的字节数
* @return 转换完成的short
*/
public static short byteToUshort(byte b) {
return (short) (b & 0x00ff);
}
/**
* 将byte转换为无符号的int类型
* @param b 需要转换的字节数
* @return 转换完成的int
*/
public static int byteToUint(byte b) {
return b & 0x00ff;
}
/**
* 将byte转换为无符号的long类型
* @param b 需要转换的字节数
* @return 转换完成的long
*/
public static long byteToUlong(byte b) {
return b & 0x00ff;
}
/**
* 将short转换为无符号的int类型
* @param s 需要转换的short
* @return 转换完成的int
*/
public static int shortToUint(short s) {
return s & 0x00ffff;
}
/**
* 将short转换为无符号的long类型
*
* @param s 需要转换的字节数
* @return 转换完成的long
*/
public static long shortToUlong(short s) {
return s & 0x00ffff;
}
/**
* 将int转换为无符号的long类型
*
* @param i 需要转换的字节数
* @return 转换完成的long
*/
public static long intToUlong(int i) {
return i & 0x00ffffffff;
}
/**
* 将short转换成小端序的byte数组
*
* @param s 需要转换的short
* @return 转换完成的byte数组
*/
public static byte[] shortToLittleEndianByteArray(short s) {
return ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN).putShort(s).array();
}
/**
* 将int转换成小端序的byte数组
*
* @param i 需要转换的int
* @return 转换完成的byte数组
*/
public static byte[] intToLittleEndianByteArray(int i) {
return ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(i).array();
}
/**
* 将long转换成小端序的byte数组
*
* @param l 需要转换的long
* @return 转换完成的byte数组
*/
public static byte[] longToLittleEndianByteArray(long l) {
return ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN).putLong(l).array();
}
/**
* 将short转换成大端序的byte数组
*
* @param s 需要转换的short
* @return 转换完成的byte数组
*/
public static byte[] shortToBigEndianByteArray(short s) {
return ByteBuffer.allocate(2).order(ByteOrder.BIG_ENDIAN).putShort(s).array();
}
/**
* 将int转换成大端序的byte数组
*
* @param i 需要转换的int
* @return 转换完成的byte数组
*/
public static byte[] intToBigEndianByteArray(int i) {
return ByteBuffer.allocate(2).order(ByteOrder.BIG_ENDIAN).putInt(i).array();
}
/**
* 将long转换成大端序的byte数组
*
* @param l 需要转换的long
* @return 转换完成的byte数组
*/
public static byte[] longToBigEndianByteArray(long l) {
return ByteBuffer.allocate(2).order(ByteOrder.BIG_ENDIAN).putLong(l).array();
}
/**
* 将short转换为16进制字符串
*
* @param s 需要转换的short
* @param isLittleEndian 是否是小端序(true为小端序false为大端序)
* @return 转换后的字符串
*/
public static String shortToHexString(short s, boolean isLittleEndian) {
byte byteArray[] = null;
if (isLittleEndian) {
byteArray = shortToLittleEndianByteArray(s);
} else {
byteArray = shortToBigEndianByteArray(s);
}
return byteArrayToHexString(byteArray);
}
/**
* 将int转换为16进制字符串
*
* @param i 需要转换的int
* @param isLittleEndian 是否是小端序(true为小端序false为大端序)
* @return 转换后的字符串
*/
public static String intToHexString(int i, boolean isLittleEndian) {
byte byteArray[] = null;
if (isLittleEndian) {
byteArray = intToLittleEndianByteArray(i);
} else {
byteArray = intToBigEndianByteArray(i);
}
return byteArrayToHexString(byteArray);
}
/**
* 将long转换为16进制字符串
*
* @param l 需要转换的long
* @param isLittleEndian 是否是小端序(true为小端序false为大端序)
* @return 转换后的字符串
*/
public static String longToHexString(long l, boolean isLittleEndian) {
byte byteArray[] = null;
if (isLittleEndian) {
byteArray = longToLittleEndianByteArray(l);
} else {
byteArray = longToBigEndianByteArray(l);
}
return byteArrayToHexString(byteArray);
}
/**
* 将字节数组转换成16进制字符串
* @param array 需要转换的字符串
* @param toPrint 是否为了打印输出,如果为true则会每4自己添加一个空格
* @return 转换完成的字符串
*/
// public static String byteArrayToHexString(byte[] array, boolean toPrint) {
// if (array == null) {
// return "null";
// }
// StringBuffer sb = new StringBuffer();
//
// for (int i = 0; i < array.length; i++) {
// sb.append(byteToHex(array[i]));
// if (toPrint && (i + 1) % 4 == 0) {
// sb.append(" ");
// }
// }
// return sb.toString();
// }
/**
* 字节数组转换成String,指定长度转换长度
* @param arrBytes
* @param count 转换长度
* @param blank 要不要空格(每个byte字节,最是否用一个“ ”隔开)
* @return "" | arrBytes换成的字符串(不存在null)
*/
public static String byteArray2HexString(byte[] arrBytes, int count, boolean blank) {
String ret = "";
if (arrBytes == null || arrBytes.length < 1)
return ret;
if (count > arrBytes.length)
count = arrBytes.length;
StringBuilder builder = new StringBuilder();
for (int i = 0; i < count; i++) {
ret = Integer.toHexString(arrBytes[i] & 0xFF).toUpperCase();
if (ret.length() == 1)
builder.append("0").append(ret);
else
builder.append(ret);
if (blank)
builder.append(" ");
}
return builder.toString();
}
public static String hexStr2Str(String hexStr) {
String string = "0123456789ABCDEF";
char[] hexs = hexStr.toCharArray();
byte[] bytes = new byte[hexStr.length() / 2];
int n;
for (int i = 0; i < bytes.length; i++) {
n = string.indexOf(hexs[2 * i]) * 16;
n += string.indexOf(hexs[2 * i + 1]);
bytes[i] = (byte) (n & 0xff);
}
return new String(bytes);
}
/**
* 将指定字符串src,以每两个字符分割转换为16进制形式 如:"2B44EFD9" --> byte[]{0x2B, 0x44, 0xEF, 0xD9}
* @param src String
* @return null | byte[]
*/
public static byte[] HexString2Bytes(String src) {
// String strTemp = "";
if (src == null || "".equals(src))
return null;
StringBuilder builder = new StringBuilder();
for (char c : src.trim().toCharArray()) {
/* 去除中间的空格 */
if (c != ' ') {
builder.append(c);
}
}
src = builder.toString();
byte[] ret = new byte[src.length() / 2];
byte[] tmp = src.getBytes();
for (int i = 0; i < src.length() / 2; i++) {
ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);
}
return ret;
}
/**
* 将两个ASCII字符合成一个字节; 如:"EF"--> 0xEF
* @param src0 byte
* @param src1 byte
* @return byte
*/
public static byte uniteBytes(byte src0, byte src1) {
byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 })).byteValue();
_b0 = (byte) (_b0 << 4);
byte _b1 = Byte.decode("0x" + new String(new byte[] { src1 })).byteValue();
byte ret = (byte) (_b0 ^ _b1);
return ret;
}
/**
* 将字节数组转换成16进制字符串
* @param array 需要转换的字符串(字节间没有分隔符)
* @return 转换完成的字符串
*/
public static String byteArrayToHexString(byte[] array) {
return byteArray2HexString(array, Integer.MAX_VALUE, false);
}
/**
* 将字节数组转换成long类型
* @param bytes 字节数据
* @return long类型
*/
public static long byteArrayToLong(byte[] bytes) {
return ((((long) bytes[0] & 0xff) << 24) | (((long) bytes[1] & 0xff) << 16) | (((long) bytes[2] & 0xff) << 8)
| (((long) bytes[3] & 0xff) << 0));
}
/**
* 合并数组
* @param firstArray 第一个数组
* @param secondArray 第二个数组
* @return 合并后的数组
*/
public static byte[] concat(byte[] firstArray, byte[] secondArray) {
if (firstArray == null || secondArray == null) {
if (firstArray != null)
return firstArray;
if (secondArray != null)
return secondArray;
return null;
}
byte[] bytes = new byte[firstArray.length + secondArray.length];
System.arraycopy(firstArray, 0, bytes, 0, firstArray.length);
System.arraycopy(secondArray, 0, bytes, firstArray.length, secondArray.length);
return bytes;
}
//字符转二进制
public static String toBinary(String str){
char[] strChar=str.toCharArray();
String result="";
for(int i=0;i<strChar.length;i++){
result +=Integer.toBinaryString(strChar[i])+ " ";
}
System.out.println(result);
return result;
}
/**
* 将16进制转换为二进制
* @param hexString
* @return
*/
public static String hexString2binaryString(String hexString) {
//16进制转10进制
BigInteger sint = new BigInteger(hexString, 16);
//10进制转2进制
String result = sint.toString(2);
//字符串反转
//return new StringBuilder(result).reverse().toString();
return result;
}
//将十六进制转换为二进制
public static byte[] parseHexStr2Byte(String str){
if(str.length() < 1)
return null;
byte[] result = new byte[str.length()/2];
for (int i = 0;i< str.length()/2; i++) {
int high = Integer.parseInt(str.substring(i*2, i*2+1), 16);
int low = Integer.parseInt(str.substring(i*2+1, i*2+2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
//将二进制字符转换为十六进制
public static String parseByte2HexStr(String str){
int i = Integer.parseInt(str,2); //将二进制转为十进制
String j = Integer.toHexString(i); //将十进制转为十六进制
return j;
}
//将二进字节数组制转换为十六进制
public static String parseByte2HexStr(byte[] binary){
StringBuffer sb = new StringBuffer();
for (byte b : binary) {
String hex = Integer.toHexString(b & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString().trim();
}
/**
* 十六进制字符串转IEEE754浮点型
* @param s
* @author: 若非
* @date: 2021/9/10 16:57
*/
public static float hexToSingle(String s ) {
BigInteger data = new BigInteger(s,16);
return Float.intBitsToFloat(data.intValue());
}
//判断字符串是否为json格式
public static boolean getJSONType(String str) {
boolean result = false;
if (!StringUtils.isBlank(str)) {
str = str.trim();
if (str.startsWith("{") && str.endsWith("}")) {
result = true;
} else if (str.startsWith("[") && str.endsWith("]")) {
result = true;
}
}
return result;
}
public static long daysBetween(Date one, Date two) {
long difference = (one.getTime()-two.getTime())/86400000;
return Math.abs(difference);
}
/** 比较两个字符串时间大小 */
public static int compareTwoTime(String time1, String time2) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
int flagValue = 0;
try {
Date date1, date2;
date1 = simpleDateFormat.parse(time1);
date2 = simpleDateFormat.parse(time2);
long millisecond = date1.getTime() - date2.getTime();
if (millisecond > 0) {
flagValue = 1;
} else if (millisecond < 0) {
flagValue = -1;
} else if (millisecond == 0) {
flagValue = 0;
}
} catch (ParseException e) {
e.printStackTrace();
}
return (flagValue);
}
/** 表两个时间差 */
public static int compareTwoTime(Date time1, Date time2) {
int flagValue = 0;
try {
long millisecond = time1.getTime() - time2.getTime();
if (millisecond > 0) {
flagValue = 1;
} else if (millisecond < 0) {
flagValue = -1;
} else if (millisecond == 0) {
flagValue = 0;
}
} catch (Exception e) {
e.printStackTrace();
}
return (flagValue);
}
/** 比较两个时间相差天数 */
public static float calculateTimeGapDay(String time1, String time2) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
float day = 0;
Date date1 = null;
Date date2 = null;
try {
date1 = simpleDateFormat.parse(time1);
date2 = simpleDateFormat.parse(time2);
long millisecond = date2.getTime() - date1.getTime();
day = millisecond / (24 * 60 * 60 * 1000);
} catch (ParseException e) {
e.printStackTrace();
}
return (day);
}
/** 比较两个时间相差天数 */
public static float calculateTimeGapDay(Date time1, Date time2) {
float day = 0;
try {
Date date1, date2;
date1 = time1;
date2 = time2;
long millisecond = date2.getTime() - date1.getTime();
day = millisecond / (24 * 60 * 60 * 1000);
} catch (Exception e) {
e.printStackTrace();
}
return (day);
}
/** 比较两个时间相差小时 */
public static double calculateTimeGapHour(String time1, String time2) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
double hour = 0;
try {
Date date1, date2;
date1 = simpleDateFormat.parse(time1);
date2 = simpleDateFormat.parse(time2);
double millisecond = date2.getTime() - date1.getTime();
hour = millisecond / (60 * 60 * 1000);
} catch (ParseException e) {
e.printStackTrace();
}
return hour;
}
/** 比较两个时间相差小时 */
public static double calculateTimeGapHour(Date date1, Date date2) {
double hour = 0;
double millisecond = date2.getTime() - date1.getTime();
hour = millisecond / (60 * 60 * 1000);
return hour;
}
/** 比较两个时间相差分钟 */
public static double calculateTimeGapMinute(String time1, String time2) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
double minute = 0;
try {
Date date1, date2;
date1 = simpleDateFormat.parse(time1);
date2 = simpleDateFormat.parse(time2);
double millisecond = date2.getTime() - date1.getTime();
minute = millisecond / (60 * 1000);
} catch (ParseException e) {
e.printStackTrace();
}
return minute;
}
/** 比较两个时间相差分钟 */
public static double calculateTimeGapMinute(Date date1, Date date2) {
double minute = 0;
double millisecond = date2.getTime() - date1.getTime();
minute = millisecond / (60 * 1000);
return minute;
}
/** 比较两个时间相差秒 */
public static double calculateTimeGapSecond(String time1, String time2) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
double second = 0;
try {
Date date1, date2;
date1 = simpleDateFormat.parse(time1);
date2 = simpleDateFormat.parse(time2);
double millisecond = date2.getTime() - date1.getTime();
second = millisecond / (1000);
} catch (ParseException e) {
e.printStackTrace();
}
return second;
}
/** 比较两个时间相差秒 */
public static double calculateTimeGapSecond(Date date1, Date date2) {
double second = 0;
double millisecond = date2.getTime() - date1.getTime();
second = millisecond / (1000);
return second;
}
public static int compareCopyTime(String time1, String time2) {
int flagValue = 0;
double millisecond =calculateTimeGapMinute(time1,time2);
if (millisecond > 180) {
flagValue = 1;
} else if (millisecond < 180) {
flagValue = -1;
} else if (millisecond == 180) {
flagValue = 0;
}
return (flagValue);
}
/**
* 浮点转16进制
* @param value
* @return
*/
public static String floatToHex(float value) {
int intValue = Float.floatToIntBits(value) & 0xFFFFFFFF;
String hexString = Integer.toHexString(intValue);
while (hexString.length() < 8) {
hexString = "0" + hexString;
}
return hexString;
}
/**
* 16进制转浮点
* @param hexString
* @return
*/
public static float hexToFloat(String hexString) {
int intBits = Integer.parseInt(hexString, 16); // 将16进制字符串解析为整数
return Float.intBitsToFloat(intBits); // 将整数值转换为浮点数
}
}