在开发过程中,一些需要使用mac地址的地方使用的参数都是byte数组形式。 但是我们大多数时候获取到的Mac地址都是字符串形式的,那么我们就需要进行一些转换。 下面的代码是基于Java实现的Mac地址字符串与byte数组之间的转换方法:
/**
* 将Mac地址字符串转换为byte数组
* @param mac Mac地址字符串,格式如:78:44:fd:c9:87:a0
* @return 该Mac地址的byte数组形式
*/
private static byte[] getMacBytes(String mac) {
byte[] macBytes = new byte[6];
String[] strArr = mac.split(":");
for (int i = 0; i < strArr.length; i++) {
int value = Integer.parseInt(strArr[i], 16);
macBytes[i] = (byte) value;
}
return macBytes;
}
/**
* 将Mac地址的数组形式转换为字符串形式
* @param macBytes mac地址的数组形式
* @return Mac地址的字符串,格式如:78:44:fd:c9:87:a0
*/
private static String getMacString(byte[] macBytes) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < macBytes.length; i++) {
builder.append(':').append(Integer.toHexString(0xFF & macBytes[i]));
}
return builder.substring(1);
}