0

我想要一种将十进制格式的 MAC 地址转换为 HEX 格式的方法。我在下面写了这个方法。你看到它有什么缺陷吗?任何应该遵循的编码实践?我在这里缺少什么吗?

public static void main(String[] args) {
    String macDec = "76.177.205.33.164.80";
    convertToHex(macDec);
    System.out.println(macDec + " should be converted to 4CB1CD21A450");
}

private static void convertToHex(String macDec) {
    String[] macs = macDec.split("\\.");
    String hexMac = null;
    StringBuffer buff = new StringBuffer();
    for(String mac : macs) {
        hexMac = Integer.toHexString(Integer.valueOf(mac));
        buff.append(hexMac.toUpperCase());
    }
    System.out.println(buff);
}
4

1 回答 1

3

您正在使用StringBuffer(引入了 java 5 StringBuilder)。你在Integer.valueOf应该使用的时候使用Integer.parseInt。我更喜欢返回结果的方法 - 让调用者显示它。而且,假设您使用的是 Java 8+,您可以使用map. 喜欢,

private static String convertToHex(String macDec) {
    return Arrays.stream(macDec.split("\\."))
            .map(mac -> Integer.toHexString(Integer.parseInt(mac)))
            .collect(Collectors.joining()).toUpperCase();
}

toUpperCase()在最后移动了。使用您认为最容易阅读的版本。

于 2020-04-24T22:20:19.140 回答