【问题标题】:Java to convert Hexidecimal to Signed 8-Bit CodeJava 将十六进制转换为有符号的 8 位代码
【发布时间】:2016-07-14 19:05:07
【问题描述】:

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

【问题讨论】:

  • 为什么“50”会保持未十六进制?我希望输出为“80 75 -32 -25”
  • 使用空格作为分隔符解析String。然后通过Integer.parseInt(String, int) 将每个值转换为基数为16 的Integer。将该值转换为 byte 以将其转换为有符号值。
  • 你是对的@Reimeus。更新问题。对此感到抱歉。

标签: java hex 8-bit


【解决方案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);
    }

}

Java

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

【讨论】:

  • 嗯似乎无法编译。我收到此错误The method stream(String[]) is undefined for the type Arrays,解决方案需要针对 JRE6。 s2 在哪里初始化?
  • Ofc 它不会为 JRE6 编译。我使用了自 JRE8 以来就存在的流。稍等,我会为JRE6重写它
  • 与 JRE 6 完美配合。我建议您使用两种解决方案更新您的答案,1 用于 Jre6,1 用于 Jre8。然后我会除了你的答案。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-27
  • 2023-02-21
  • 2014-01-15
  • 2017-06-28
  • 2019-01-01
  • 2014-05-05
  • 2014-03-01
相关资源
最近更新 更多