我需要将表示为String的Hexideciamal数字转换为有符号的8位字符串。
例如:给定此代码段:
String hexideciaml = new String("50 4b e0 e7");
String signed8Bit = convertHexToSigned8Bit(hexideciaml);
System.out.print(signed8Bit);
输出应为: " 80 75 -32 -25"
所以我非常想用Java实现这个网站的一部分。 https://www.mathsisfun.com/binary-decimal-hexadecimal-converter.html
更新:解决方案需要适用于没有其他JAR的JRE6。
答案 0 :(得分:3)
Java 1.8(流)
import java.util.Arrays;
public class HexToDec {
public static String convertHexToSigned8Bit(String hex) {
return Arrays
.stream(hex.split(" +"))
.map(s -> "" + (byte) Integer.parseInt(s, 16))
.reduce((s, s2) -> s + " " + s2)
.get();
}
public static void main(String[] args) {
String hexidecimal = "50 4b e0 e7";
String signed8Bit = convertHexToSigned8Bit(hexidecimal);
System.out.print(signed8Bit);
}
}
Java< 1.8
import java.util.Arrays;
public class HexToDec {
public static String convertHexToSigned8Bit(String hex) {
String[] tokens = hex.split(" +");
StringBuilder result = new StringBuilder();
for (int i = 0; i < tokens.length - 1; i++) { //append all except last
result.append((byte) Integer.parseInt(tokens[i], 16)).append(" ");
}
if (tokens.length > 1) //if more than 1 item in array, add last one
result.append((byte) Integer.parseInt(tokens[tokens.length - 1], 16));
return result.toString();
}
public static void main(String[] args) {
String hexidecimal = "50 4b e0 e7";
String signed8Bit = convertHexToSigned8Bit(hexidecimal);
System.out.print(signed8Bit);
}
}
输出为:80 75 -32 -25