我只想弄清楚如何将int数转换为byte。 这听起来很容易,但对我来说很难知道如何转换它。
例如:
public byte[] getByteArray(String ipOrMac){
String[] temp = new String[0];
ArrayList<Integer> intList = new ArrayList<Integer>();
if(ipOrMac.contains(":")){
temp = ipOrMac.split(":"); // this makes temp into a new Array
//with splitted strings
}
if(ipOrMac.contains(".")){
temp = ipOrMac.split(".");
}
for(int a = 0; a<=temp.length-1; a++){
intList.add(Integer.parseInt(temp[a]));
}
// System.out.println(stringList.toArray()[0]);
// for(int a = 0; a<=stringList.size()-1; a++){
// stringList.
// }
return null;
}
我的maintarget是得到一个像这样的字符串“2:2:2:2”(这是一个mac-adress) 变成一个字节[]。 所以现在我有问题将我的arraylist-integer中的所有int转换为字节。 我不想使用arraylist-byte,因为它效率低......
所有想法?
希望你能帮助我。 :)答案 0 :(得分:2)
相反,写一下
byte[] bytes = new byte[temp.length];
for(int a = 0; a< temp.length; a++){
bytes[a] = (byte) Integer.parseInt(temp[a]);
}
return bytes;
答案 1 :(得分:1)
这个例子怎么样:
try {
ByteBuffer bb = ByteBuffer.allocate(16);
bb.order(ByteOrder.LITTLE_ENDIAN);
String[] arrSidParts = strSid.split("-");
for (int i = 4; i < arrSidParts.length; i++) {
bb.putInt((int) Long.parseLong(arrSidParts[i]));
}
Guid guid = new Guid(bb.array(), false);
out.println(guid.toString());
} catch (Exception e) {
out.println("!" + e.getMessage() + "!");
e.printStackTrace();
}
答案 2 :(得分:1)
您可以尝试以下代码段:
String[] temp = ipOrMac.split(ipOrMac.contains(":") ? ":" : "\\.");
byte[] array = new byte[temp.length];
for(int i = 0; i < temp.length; ++i)
array[i] = (byte)Integer.parseInt(temp[i]);
答案 3 :(得分:0)
如果我理解正确...你想将字符串转换为byte [],对吧?
你只需要这样做:
byte [] ipOrMacBytes = ipOrMac.getBytes();