Wednesday, June 1, 2011

Mac Address String to byte[]

The Android SDK returns a String mac address, while the Java SDK returns a byte array. This makes it somewhat difficult to compare the two.

Android:
WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = manager.getConnectionInfo();
String address = info.getMacAddress());
Java SDK
InetAddress inet = InetAddress.getLocalHost();
NetworkInterface ni = NetworkInterface.getByInetAddress(inet);
byte[] address = ni.getHardwareAddress();
The code below illustrates how to convert the string returned by Android, into a byte[].
public static byte[] parseMacAddress(String macAddress)
    {
        String[] bytes = macAddress.split(":");
        byte[] parsed = new byte[bytes.length];

        for (int x = 0; x < bytes.length; x++)
        {
            BigInteger temp = new BigInteger(bytes[x], 16);
            byte[] raw = temp.toByteArray();
            parsed[x] = raw[raw.length - 1];
        }
        return parsed;
    }

0 comments: