【问题标题】:How to convert a int to byte? [duplicate]如何将int转换为字节? [复制]
【发布时间】:2016-03-02 21:57:00
【问题描述】:

我只是想弄清楚如何将 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,因为它效率低下……” 程序变慢是因为它们做的事情太多。除非你用 List 做一百万次,否则没有理由考虑微优化,更不用说围绕它设计程序了。
  • @Radiodef,提示“过早的优化是万恶之源”。

标签: java arraylist int byte bytearray


【解决方案1】:

改为写

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

【讨论】:

  • 日本人很好。现在我必须避免负数 0 到 -127。 :) 谢谢!
  • @Cem 重要的是要明白,不,你不知道。有那些负字节是正确的。
  • 是的,但你不能在 mac- 或 ipadresse 中使用负数。
  • @Cem 正确的解决方案是将这些字节视为无符号或期望其他 API 正确处理它们。了解负字节实际上并没有错对于正确使用 Java 非常重要。
  • 我必须查看文档。但我认为 API 正在正确处理字节。我正在使用 jnetpcap 创建一个包含许多数据包的 pcap..
【解决方案2】:

你可以试试下面的sn-p代码:

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

【讨论】:

  • 行数更少的相同解决方案。 ty
  • 现在我必须避免负数。
  • 又是我。 String.split(".") 无法识别“.”....为什么?
  • Ok 发现错误。为了 ”。”我必须使用 String.split(Pattern.quote(".")); :)
  • @Cem,是的,你是对的。您应该使用"\\." 而不是"."
【解决方案3】:

这个例子怎么样:

(完整代码: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();
    }

【讨论】:

  • 那些 ByteBuffer 会自动避免负数? (从 0 到 -127)?
【解决方案4】:

如果我理解正确的话……你想把字符串转换成字节[],对吧?

你只需要这样做:

字节[] ipOrMacBytes = ipOrMac.getBytes();

【讨论】:

  • 这不太可能完成OP想要的,即获取字符串中数字的实际数值。
猜你喜欢
  • 2011-09-16
  • 2016-03-04
  • 2016-02-20
  • 1970-01-01
  • 2012-07-04
  • 2011-06-18
  • 1970-01-01
相关资源
最近更新 更多