有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

hex Java将十六进制转换为带符号的8位代码

我需要将表示为字符串的十六进制数转换为有符号的8位字符串

例如:给定以下代码片段:

String hexideciaml = new String("50  4b e0  e7");
String signed8Bit = convertHexToSigned8Bit(hexideciaml);
System.out.print(signed8Bit);

输出应为: “8075-32-25”

所以我非常想用Java实现这个网站的一部分https://www.mathsisfun.com/binary-decimal-hexadecimal-converter.html

更新:解决方案需要适用于JRE6,无需其他JAR


共 (1) 个答案

  1. # 1 楼答案

    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);
        }
    
    }
    

    爪哇<;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);
        }
    
    }
    

    输出为:8075-32-25