Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

android

hex

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

like image 489
Mr.Noob Avatar asked May 31 '12 14:05

Mr.Noob


1 Answers

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();
}
like image 180
Ben Holland Avatar answered Oct 28 '22 11:10

Ben Holland