的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
爲什麼會在 「50」 仍然unhexified?我希望輸出爲「80 75 -32 -25」 – Roshan
使用空格作爲分隔符解析'String'。然後通過'Integer.parseInt(String,int)'將每個值轉換爲一個基數爲16的Integer。將該值轉換爲'byte'將其轉換爲有符號值。 –
你是對的@Reimeus。更新問題。對於那個很抱歉。 – javaPlease42