How to convert a Mac Address to a Hex and pass it to a bytearray in java

17,468

Solution 1

A MAC address is already in hexadecimal format, it is of the form of 6 pairs of 2 hexadecimal digits.

String macAddress = "AA:BB:CC:DD:EE:FF";
String[] macAddressParts = macAddress.split(":");

// convert hex string to byte values
Byte[] macAddressBytes = new Byte[6];
for(int i=0; i<6; i++){
    Integer hex = Integer.parseInt(macAddressParts[i], 16);
    macAddressBytes[i] = hex.byteValue();
}

And...

String ipAddress = "192.168.1.1";
String[] ipAddressParts = ipAddress.split("\\.");

// convert int string to byte values
Byte[] ipAddressBytes = new Byte[4];
for(int i=0; i<4; i++){
    Integer integer = Integer.parseInt(ipAddressParts[i]);
    ipAddressBytes[i] = integer.byteValue();
}

Solution 2

The open-source IPAddress Java library will parse both MAC addresses and IP addresses, and convert to bytes in a polymorphic manner. Disclaimer: I am the project manager of that library.

The following code will do what you are requesting:

    String ipv4Addr = "1.2.3.4";
    String ipv6Addr = "aaaa:bbbb:cccc:dddd::";
    String macAddr = "a:b:c:d:e:f";
    try {
        HostIdentifierString addressStrings[] = {
            new IPAddressString(ipv4Addr),
            new IPAddressString(ipv6Addr),
            new MACAddressString(macAddr)
        };
        Address addresses[] = new Address[addressStrings.length];
        for(int i = 0; i < addressStrings.length; i++) {
            addresses[i] = addressStrings[i].toAddress();//parse
        }
        for(Address addr : addresses) {
            byte bytes[] = addr.getBytes();
            //convert to a list of positive Integer for printing
            List<Integer> forPrinting = IntStream.range(0, bytes.length).map(idx -> 0xff & bytes[idx]).boxed().collect(Collectors.toList());
            System.out.println("bytes for " + addr + " are " + forPrinting);
        }
    } catch(HostIdentifierException | IOException e) {
        //e.getMessage has validation error
    }

output:

    bytes for 1.2.3.4 are [1, 2, 3, 4]
    bytes for aaaa:bbbb:cccc:dddd:: are [170, 170, 187, 187, 204, 204, 221, 221, 0, 0, 0, 0, 0, 0, 0, 0]
    bytes for 0a:0b:0c:0d:0e:0f are [10, 11, 12, 13, 14, 15]
Share:
17,468
Mr.Noob
Author by

Mr.Noob

Updated on June 09, 2022

Comments

  • Mr.Noob
    Mr.Noob almost 2 years

    How can i convert a MacAddress to a Hex String and then parse it to a byte in java? and similarly an IP Address as well?

    Thank you