如何将 int 转换为 byte?

How to convert a int to byte?

我只是想弄清楚如何将 int 数字转换为字节。 听起来很简单,但对我来说很难知道如何转换它。

例如:

    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;
    }

我的主要目标是获得像这样的字符串“2:2:2:2”(它是一个 mac-地址) 成一个字节[]。 所以现在我遇到了将 arraylist-integer 中的所有整数转换为字节的问题。 我不想使用 arraylist-byte,因为它效率低下...

有什么想法吗?

希望你能帮助我。 :)

如果我没理解错的话……你想把字符串转换成 byte[],对吧?

您只需要这样做:

byte[] ipOrMacBytes = ipOrMac.getBytes();

改为写

    byte[] bytes = new byte[temp.length];
    for(int a = 0; a< temp.length; a++){
        bytes[a] = (byte) Integer.parseInt(temp[a]);
    }
    return bytes;

这个例子怎么样:

(完整代码:https://github.com/anjalshireesh/gluster-ovirt-poc/blob/master/backend/manager/modules/utils/src/test/java/org/ovirt/engine/core/utils/jwin32/AppTest.java#L153

    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();
    }

您可以试试下面的代码片段:

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]);