/**********************************时间类**********************************/
/**
* utc国际标准时间,转化成date,格式为:"20140823T092005Z"
*/
public static Date utcToLocalDate(String date){
try{
SimpleDateFormat df1 = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
df1.setTimeZone(TimeZone.getTimeZone("UTC"));
return df1.parse(date);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
/**********************************数据类型**********************************/
/**
* 十进制转换成二进制字符串,不足8位补0
*/
public static String intToBinary(int data){
String binaryStr = Integer.toBinaryString(data);
int len = binaryStr.length();
for(int i=0; i<8-len; i++){
binaryStr = "0" + binaryStr;
}
return binaryStr;
}
/**
* 将double格式化为指定小数位的String,不足小数位用0补全
*
* @param data 需要格式化的数字
* @param scale 小数点后保留几位
* @return
*/
public static String roundByScale(double data, int scale) {
if (scale < 0) {
throw new IllegalArgumentException(
"The scale must be a positive integer or zero");
}
if(scale == 0){
return new DecimalFormat("0").format(data);
}
String formatStr = "0.";
for(int i=0;i<scale;i++){
formatStr = formatStr + "0";
}
return new DecimalFormat(formatStr).format(data);
}
/**
* bytes转16进制
*/
public static String bytesToHexString(byte[] src){
StringBuilder sb = 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) {
sb.append(0);
}
sb.append(hv);
}
return sb.toString();
}
/**
* bytes转16进制
* 一个byte为8位,可用两个十六进制位标识
*/
public static String bytesToHexFun2() {
byte[] bytes = {22,10,1,1,1};
char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5','6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
char[] buf = new char[bytes.length * 2];
int index = 0;
for(byte b : bytes) {
buf[index++] = HEX_CHAR[b >>> 4 & 0xf];
buf[index++] = HEX_CHAR[b & 0xf];
}
return new String(buf);
}
/**
* float-->byte[]
* 注意高低位
*/
public static byte[] getBytesFromFloat(float f){
byte[] dataBytes = new byte[4];
int intBits = Float.floatToIntBits(f);
dataBytes[3] = (byte) ((intBits >> 24) & 0xFF);
dataBytes[2] = (byte) ((intBits >> 16) & 0xFF);
dataBytes[1] = (byte) ((intBits >> 8) & 0xFF);
dataBytes[0] = (byte) ((intBits) & 0xFF);
return dataBytes;
}
/**
* 字节转换为浮点
* 注意高低位
*/
public static float byte2float(byte[] b, int index) {
int l;
l = b[index + 3];
l &= 0xff;
l |= ((long) b[index + 2] << 8);
l &= 0xffff;
l |= ((long) b[index + 1] << 16);
l &= 0xffffff;
l |= ((long) b[index + 0] << 24);
return Float.intBitsToFloat(l);
}
java小工具类
最新推荐文章于 2022-05-31 21:11:21 发布