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

标签 java hex 8-bit

我需要将表示为字符串的十六进制数字转换为带符号的 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,没有其他 Jars。

最佳答案

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

关于Java 将十六进制转换为带符号的 8 位代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38382295/

相关文章:

c - int8 数组与标量的快速乘法

java - 当 jar 通过命令行运行时,相对路径不起作用,但通过 Netbean 运行时,相对路径起作用

java - 在野蝇关闭时使用数据源

c - 从c中的标准输入读取十六进制

c++ - 声明一个十六进制数的数组

java - MD5 哈希不同

java - 无法弄清楚如何显示对象数组Java

java - Java Mission Control Flight Recorder 中没有记录 CPU 使用情况

php - 尝试通过 Socket 向 ZVT 终端发送数据

python - 在 Python 中减去 8 位整数