0

I want a method to convert a decimal format MAC address to HEX format. I have written this below method. Do you see any flaws in it? Any coding practices that should be followed? Anything I am missing here?

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

1 Answer 1

3

You're using StringBuffer (java 5 introduced StringBuilder). You're using Integer.valueOf when you should be using Integer.parseInt. I would prefer a method that returned a result - let the caller display it. And, assuming you're using Java 8+, you could just stream and convert with a map. Like,

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

I moved the toUpperCase() at the end. Use whichever version you find easiest to read.

Sign up to request clarification or add additional context in comments.

4 Comments

How do we make this method return Optional<String>? Wrapping it with Optional.of doesn't seem clean. private static String convertToHex(String macDec) { return Optional.of(Arrays.stream(macDec.split("\\.")) .map(mac -> Integer.toHexString(Integer.parseInt(mac))) .collect(Collectors.joining()).toUpperCase()); }
Why should it be an optional String? Your posted version was void.
I understand. I am just asking. I forgot to use Optional earlier. I learnt using Optional is a best practice.
My version can never return null. So making it optional just introduces an extra layer of complexity. It might throw an exception, but in all other cases where something might return null (including "") it should return "". Anyway, you could use Optional.ofNullable if you want to be silly. I'm not the Java cops. And Optional only has a few factory methods available.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.