当我运行它(它是Android应用程序的一部分)时,它可以工作。
String[] hex = new String[6];
hex[0] = "A4";
hex[1] = "8A";
hex[2] = "5B";
hex[3] = "9O";
hex[4] = "U4";
hex[5] = "D8";
if (hex.length != 6) {
throw new IllegalArgumentException("Invalid MAC address.");
}
try {
for (int i = 0; i < 6; i++) {
bytes[i] = (byte) Integer.parseInt(hex[i], 16);
}
}
catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid hex digit in MAC address.");
}
但如果我这样做:
String[] hex = macStr.split("(\\:|\\-)");
if (hex.length != 6) {
throw new IllegalArgumentException("Invalid MAC address.");
}
try {
for (int i = 0; i < 6; i++) {
bytes[i] = (byte) Integer.parseInt(hex[i], 16);
}
}
catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid hex digit in MAC address.");
}
它不起作用...... 我试图找到问题,似乎第一个十六进制与第二个不同;但如果我做一个println,他们似乎是相同的。
答案 0 :(得分:0)
使用masStr.split("[:\\-]")
分隔' - '和':'符号。
如果它不起作用(我只是测试它以防万一 - 它工作) - 检查你的输入
答案 1 :(得分:0)
您正在解析xx-xx-xx-xx-xx-xx
或yy:yy:yy:yy:yy:yy
表单中的mac地址
你的分裂方法是有效的。但你可能会错过的是数组的初始化。数组是固定长度的。它应该用大小来定义。
byte[] bytes;
String macStr="ab:ab-cd:ab:ab-cd";
String[] hex = macStr.split("(\\:|\\-)");
System.out.println(hex.length);
if (hex.length != 6) {
throw new IllegalArgumentException("Invalid MAC address.");
}
try {
bytes=new byte[6];
for (int i = 0; i < 6; i++) {
bytes[i] = (byte) Integer.parseInt(hex[i], 16);
}
}
catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid hex digit in MAC address.");
}