前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java进制各种转换

java进制各种转换

原创
作者头像
IT工作者
发布2022-05-09 10:52:26
9150
发布2022-05-09 10:52:26
举报
文章被收录于专栏:程序技术知识
代码语言:javascript
复制
public class BDUtils {


/**
* String -> Hex
* 
* @param s
* @return
*/
public static String stringToHex(String s) {
String str = "";
for (int i = 0; i < s.length(); i++) {
int ch = s.charAt(i);
String s4 = Integer.toHexString(ch);
if (s4.length() == 1) {
s4 = '0' + s4;
}
str = str + s4 + " ";
}
return str;
}


/**
* String -> Hex
* 
* @param s
* @return
*/
public static String stringToHexAll(String s) {
String str = "";
for (int i = 0; i < s.length(); i++) {
int ch = (int) s.charAt(i);
String s4 = Integer.toHexString(ch);
if (s4.length() == 1) {
s4 = '0' + s4;
}
str = str + s4;
}
return str;
}


/**
* Hex -> String
* 
* @param s
* @return
*/
public static String hexToString(String s) {
String[] strs = s.split(" ");
byte[] baKeyword = new byte[strs.length];
for (int i = 0; i < baKeyword.length; i++) {
try {
baKeyword[i] = (byte) (0xff & Integer.parseInt(strs[i], 16));
} catch (Exception e) {
e.printStackTrace();
}
}
try {
s = new String(baKeyword, "utf-8");// UTF-16le:Not
} catch (Exception e1) {
e1.printStackTrace();
}
return s;
}


/**
* Hex -> String
* 
* @param s
* @return
*/
public static String hexToStringGBK(String s) {
String[] strs = s.split(" ");
byte[] baKeyword = new byte[strs.length];
for (int i = 0; i < baKeyword.length; i++) {
try {
baKeyword[i] = (byte) (0xff & Integer.parseInt(strs[i], 16));
} catch (Exception e) {
e.printStackTrace();
}
}
try {
s = new String(baKeyword, "GBK");// UTF-16le:Not
} catch (Exception e1) {
e1.printStackTrace();
}
return s;
}


/**
* Hex -> Byte
* 
* @param s
* @return
* @throws Exception
*/
public static byte[] hexToByte(String s) throws Exception {
if ("0x".equals(s.substring(0, 2))) {
s = s.substring(2);
}
Log.d("BDUtils==hexToByte==", s);
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();
throw e;
}
}


return baKeyword;
}


public static int getINTFromByte(byte[] buffer) {
int a = 0;
a = (0xff000000 & (((int) buffer[0]) << 24) | 0x00ff0000
& (((int) buffer[1]) << 16) | 0x0000ff00
& (((int) buffer[2]) << 8) | 0x000000ff & (((int) buffer[3]) << 0));
return a;
}


@SuppressWarnings("unused")
private byte[] getBytesFromInt(int length) {
byte b[] = new byte[4];
b[0] = (byte) (length >> 24 & 0xFF);
b[1] = (byte) (length >> 16 & 0xFF);
b[2] = (byte) (length >> 8 & 0xFF);
b[3] = (byte) (length >> 0 & 0xFF);
return b;
}


public static int byte2int(byte[] res) {
// res = InversionByte(res);
// 一个byte数据左移24位变成0x??000000,再右移8位变成0x00??0000
int targets = (res[0] & 0xff) | ((res[1] << 8) & 0xff00); // | 表示安位或
return targets;
}


public static int unsignedByteToInt(byte b) {
return (int) b & 0xFF;
}


/**
* Byte -> Hex
* 
* @param bytes
* @return
*/
public static String byteToHex(byte[] bytes, int count) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < count; i++) {
String hex = Integer.toHexString(bytes[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex).append(" ");
}
return sb.toString();
}


@SuppressWarnings("unused")
private static String transSMSContent(String[] strs, int start, int len) {
String temp = "";
String tt;
for (int i = start; i < start + len; i++) {
temp += strs[i] + " ";
}
tt = hexToStringGBK(temp); // C4e3
return tt;


}


public static String toStringHex(String s) {
if ("0x".equals(s.substring(0, 2))) {
s = s.substring(2);
}
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-16le:Not
s = new String(baKeyword, "utf-8");// UTF-16le:Not
} catch (Exception e1) {
e1.printStackTrace();
}
return s;
}


public static String getLocalTime() {
//
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
return getMonth(month) + "-" + day + " " + hour + ":" + minute + ":"
+ second;
//
// SimpleDateFormat sDateFormat = new
// SimpleDateFormat("yyyy-MM-dd   hh:mm:ss");
// String date = sDateFormat.format(new java.util.Date());
// return date;


// DateFormat
// df=DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT,Locale.CHINA);
// // System.out.println(df.format(new Date()));
// return df.format(new Date());
}


public static boolean checkSum(String[] strArray) {
boolean result = false;
String content = "";
String CRC = strArray[(strArray.length - 1)];
// 校验和数据
for (int i = 0; i < strArray.length - 1; i++) {
content += strArray[i];
}
String strSum = doCheckSum(content);
if ((strSum.toUpperCase()).equals(CRC.toUpperCase()))
result = true;
return result;
}


/**
* 计算校验和
*/
public static String doCheckSum(String msg) {
// String msg = "2458545A4A000D0679DC0005";
byte cmdBytes[] = null;
int i;
byte bt;
try {
cmdBytes = hexToByte(msg);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (bt = cmdBytes[0], i = 1; i < cmdBytes.length; i++) {
bt ^= cmdBytes[i];
}


String hex = Integer.toHexString(bt & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}


return hex;
}


public static String transHexString(String str) {
try {
return String.valueOf(ByteArray2Int(hexToByte(str)));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}


// 格式化辅助函数
public static byte[] Int2ByteArray(int iSource, int iArrayLen) {
byte[] bLocalArr = new byte[iArrayLen];
for (int i = 0; (i < 4) && (i < iArrayLen); i++) {
bLocalArr[i] = (byte) (iSource >> 8 * i & 0xFF);
}
return bLocalArr;
}


public static int ByteArray2Int(byte[] bRefArr) {
int iOutcome = 0;
byte bLoop;


for (int i = 0; i < bRefArr.length; i++) {
bLoop = bRefArr[i];
iOutcome += (bLoop & 0xFF) << (8 * i);


}
return iOutcome;
}


/*
* 将字符串编码成16进制数字,适用于所有字符(包括中文)
*/
public static String encode(String str, String charSet) {
// 根据默认编码获取字节数组
byte[] bytes = null;
try {
bytes = str.getBytes(charSet);
StringBuilder sb = new StringBuilder(bytes.length * 2);
// 将字节数组中每个字节拆解成2位16进制整数
for (int i = 0; i < bytes.length; i++) {
sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));
sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0));
}
return sb.toString();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;


}


public static String decode(String hexStr) {
if (null == hexStr || "".equals(hexStr) || (hexStr.length()) % 2 != 0) {
return null;
}


int byteLength = hexStr.length() / 2;
byte[] bytes = new byte[byteLength];


int temp = 0;
for (int i = 0; i < byteLength; i++) {
temp = hex2Dec(hexStr.charAt(2 * i)) * 16
+ hex2Dec(hexStr.charAt(2 * i + 1));
bytes[i] = (byte) (temp < 128 ? temp : temp - 256);
}
return new String(bytes);


}


private static String hexString = "0123456789ABCDEF";


private static int hex2Dec(char ch) {
if (ch == '0')
return 0;
if (ch == '1')
return 1;
if (ch == '2')
return 2;
if (ch == '3')
return 3;
if (ch == '4')
return 4;
if (ch == '5')
return 5;
if (ch == '6')
return 6;
if (ch == '7')
return 7;
if (ch == '8')
return 8;
if (ch == '9')
return 9;
if (ch == 'a')
return 10;
if (ch == 'A')
return 10;
if (ch == 'B')
return 11;
if (ch == 'b')
return 11;
if (ch == 'C')
return 12;
if (ch == 'c')
return 12;
if (ch == 'D')
return 13;
if (ch == 'd')
return 13;
if (ch == 'E')
return 14;
if (ch == 'e')
return 14;
if (ch == 'F')
return 15;
if (ch == 'f')
return 15;
else
return -1;


}


/*
* 将16进制数字解码成字符串,适用于所有字符(包括中文)
*/
public static String decodestr(String str, String charSet) {
try {
byte[] bytes = new byte[(str.length() + 1) / 2];
for (int i = 0, l = 0; i < str.length(); i += 2, l++) {
int j = Integer.parseInt(str.charAt(i) + "", 16);
int k = 0;
if (i + 1 < str.length()) {
k = Integer.parseInt(str.charAt(i + 1) + "", 16);
}
int b = (j << 4);
bytes[l] = (byte) (b + k);
}
return new String(bytes, charSet);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "";
}


// 十进制转十六进制
public static String D2X(int d) {
String x = "";
if (d < 16) {
x = change(d);
} else {
int c;
int s = 0;
int n = d;
@SuppressWarnings("unused")
int temp = d;
while (n >= 16) {
s++;
n = n / 16;
}
String[] m = new String[s];
int i = 0;
do {
c = d / 16;
m[i++] = change(d % 16);
d = c;
} while (c >= 16);
x = change(d);
for (int j = m.length - 1; j >= 0; j--) {
x += m[j];
}
}
if (x.length() == 3) {
x = "0" + x;
} else if (x.length() == 2) {
x = "00" + x;
} else if (x.length() == 1) {
x = "000" + x;
}
return x;
}


public static String change(int d) {
String x = "";
switch (d) {
case 10:
x = "A";
break;
case 11:
x = "B";
break;
case 12:
x = "C";
break;
case 13:
x = "D";
break;
case 14:
x = "E";
break;
case 15:
x = "F";
break;
default:
x = String.valueOf(d);
break;
}
return x;
}


// 十进制转十六进制
public static String Decimal2X(int d) {
String x = "";
if (d < 16) {
x = change(d);
} else {
int c;
int s = 0;
int n = d;
@SuppressWarnings("unused")
int temp = d;
while (n >= 16) {
s++;
n = n / 16;
}
String[] m = new String[s];
int i = 0;
do {
c = d / 16;
m[i++] = change(d % 16);
d = c;
} while (c >= 16);
x = change(d);
for (int j = m.length - 1; j >= 0; j--) {
x += m[j];
}
}
if (x.length() % 2 == 1) {
x = "0" + x;
}
return x;
}


public static String getMonth(int month) {
if (month < 10) {
return "" + 0 + month;
} else {
return "" + month;
}
}
}

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档