Java 将十六进制转换为带符号的 8 位代码
Java to convert Hexidecimal to Signed 8-Bit Code
我需要将表示为字符串的十六进制数字转换为带符号的 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
更新: 解决方案需要针对 JRE6,没有其他 Jar。
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
我需要将表示为字符串的十六进制数字转换为带符号的 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
更新: 解决方案需要针对 JRE6,没有其他 Jar。
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