我正在使用此代碼來查找計算機的MAC地址。此代碼直接打印MAC地址,但我想將其作爲字符串返回。我完全困惑。將MAC地址字節數組格式化爲字符串
請大家幫忙。
try {
InetAddress add = InetAddress.getByName("10.123.96.102");
NetworkInterface ni1 = NetworkInterface.getByInetAddress(add);
if (ni1 != null) {
byte[] mac1 = ni1.getHardwareAddress();
if (mac1 != null) {
for (int k = 0; k < mac1.length; k++) {
System.out.format("%02X%s", mac1[k], (k < mac1.length - 1) ? "-" : "");
}
} else {
System.out.println("Address doesn't exist ");
}
System.out.println();
} else {
System.out.println("address is not found.");
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
}
如果您需要以相同的方式返回格式化的字符串,請使用StringBuilder,並將其附加到以String.format(..)格式設置的循環部分中。 – 2010-05-09 11:09:44
見http://stackoverflow.com/questions/311165/how-do-you-convert-byte-array-to-hexadecimal-string-and-vice-versa-in-c/632920#632920 – Zaki 2010-05-09 11:11:11