# 进制之间的转换(16进制转换二进制、二进制转换十进制、整型转换十六进制高低字节排序)

1.整型转换十六进制并进行高低字节排序

// 整型转换16进制并排序
public static String decToHex(Integer dec) {
StringBuilder hex = new StringBuilder();
while (dec != 0) {
String h = Integer.toString(dec & 0xff, 16);
if ((h.length() & 0x01) == 1)
h = '0' + h;
hex.append(h);
dec = dec >> 8;
}
return hex.toString();
}

2、十六进制转换二进制

// 十六进制转换二进制
public static String hexStr2BinArr(String hexString) {
String[] binaryArray = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"};
String outStr = "";
String hexStr = "0123456789ABCDEF";
//hexString的长度对2取整，作为bytes的长度
int len = hexString.length() / 2;
byte[] bytes = new byte[len];
byte high = 0;//字节高四位
byte low = 0;//字节低四位
for (int i = 0; i < len; i++) {
//右移四位得到高位
high = (byte) ((hexStr.indexOf(hexString.charAt(2 * i))) << 4);
low = (byte) hexStr.indexOf(hexString.charAt(2 * i + 1));
bytes[i] = (byte) (high | low);//高地位做或运算
}
int pos = 0;
for (byte b : bytes) {
//高四位
pos = (b & 0xF0) >> 4;
outStr += binaryArray[pos];
//低四位
pos = b & 0x0F;
outStr += binaryArray[pos];
}
return outStr;
}

3、二进制转换十进制

// 二进制转换十进制
public static int scale2Decimal(String number, int scale) {
//checkNumber(number);
if (2 > scale || scale > 32) {
throw new IllegalArgumentException("scale is not in range");
}
// 不同其他进制转十进制,修改这里即可
int total = 0;
String[] ch = number.split("");
int chLength = ch.length;
for (int i = 0; i < chLength; i++) {
total += Integer.parseInt(ch[i]) * Math.pow(scale, chLength - 1 - i);
}
}

// 此方法判断输入的是否是数字
public static void checkNumber(String number) {
String regexp = "^\\d+\$";
if (null == number || !number.matches(regexp)) {
throw new IllegalArgumentException("input is not a number");
}
}

4、字符串转换ASCII码

/*字符串转化为ASCII码*/
private static String stringToAscii(String data) {
StringBuilder result = new StringBuilder();
if (StringUtils.isNotEmpty(data)) {
for (int i = 0; i < data.length(); i++) {
result.append(Integer.toHexString(data.charAt(i) + 0));
}
}
return result.toString();
}

5、16进制字符串转换成ASCII

// 16进制字符串转换为ASCII
public static String convertHexToString(String hex) {
StringBuilder sb = new StringBuilder();
StringBuilder temp = new StringBuilder();
for (int i = 0; i < hex.length() - 1; i += 2) {
String output = hex.substring(i, (i + 2));
//十六进制转换为十进制
int decimal = Integer.parseInt(output, 16);
//将十进制转换为字符
sb.append((char) decimal);
temp.append(decimal);
}
return sb.toString();
}

6、ASCII转换16进制

// ASCII码转换为16进制
public static String convertStringToHex(String str) {

char[] chars = str.toCharArray();

StringBuffer hex = new StringBuffer();
for (int i = 0; i < chars.length; i++) {
hex.append(Integer.toHexString((int) chars[i]));
}

return hex.toString();
}
• 0
点赞
• 0
评论
• 0
收藏
• 打赏
• 扫一扫，分享海报

12-04 3万+

02-26 1566
06-17
08-29
06-10 2657
08-14 1644
08-23 951
04-15 4496
05-21 2089
04-29 10万+
07-23 9503
08-13 3787

、无忧

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。