【问题标题】:How to store a big integer valueintoan ArrayList of Byte如何将大整数值存储到字节的 ArrayList
【发布时间】:2013-11-17 06:32:37
【问题描述】:

如何将 int value=100,000 存储到 ArrayList<Byte> 中。我不能输入 cast 因为值会改变。

是否有任何机制可以让我在 Arraylist 中分配 4 个字节并存储整数。

或者是否可以使用 byte[] 数组?

【问题讨论】:

    标签: java


    【解决方案1】:

    或者是否可以使用 byte[] 数组?

    是的,BigInteger 有一个方法toByteArray()

    byte[] resultBArray= yourBigInteger.toByteArray();
    

    即使那样你也不能存储在ArrayList<Byte>,因为Byte[]不是Byte

    但这对我来说似乎不太好,你可以带个人List 和Byte[] 或直接List<BigInteger>

    BigInteger yourBigInteger = new BigInteger(String.valueOf(100000));
    byte[] resultBArray= yourBigInteger.toByteArray();
    

    找回来

     int i=    new BigInteger(bytes).intValue();
    

    【讨论】:

    • 我有一个 int value=100000;我如何存储这个?它不是整数对象。
    • 您可以从原语创建一个 Wrapper 对象。喜欢stackoverflow.com/questions/3878192/…
    • 为什么我必须将其转换为 bigInteger?我可以把它作为整数吗?
    • @james 那就是蛋糕上的樱桃 :) Integer intObj = new Integer(100000);
    • 这不起作用,你能告诉我这里有什么问题吗? int value=100000;Integer intObj = new Integer(value); byte[] resultBArray= intObj.toByteArray();//这里出错
    【解决方案2】:

    试试:

    BigInteger value=new BigInteger("100000");
    List<byte[]> list=new   ArrayList<>();
    list.add(value.toByteArray());//Put BigInteger as byte[]
    
    BigInteger returnValue= new BigInteger(list.get(0));// Return value from list
    System.out.println(returnValue);
    

    【讨论】:

      【解决方案3】:

      做事

       byte[] byteArray = new BigInteger("100000").toByteArray();
       List<Byte> bytes = new ArrayList<>();
          for(byte b : byteArray)
              bytes.add(b);
      

      【讨论】:

      • 添加没问题。你怎么能把它拿回来?如果 OP 添加两个数字会怎样?
      • 为什么OP要加两个数字?为了取回它,他可以做 BigInteger big = new BigInteger(byteArray);
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-09
      • 2018-11-15
      • 1970-01-01
      • 2013-12-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多