集册 Java实例教程 将字节数组解析并格式化为二进制、八进制和十六进制

将字节数组解析并格式化为二进制、八进制和十六进制

欢马劈雪     最近更新时间:2020-01-02 10:19:05

379
将字节数组解析并格式化为二进制、八进制和十六进制

import java.math.BigInteger;

/* 
 来自 
*时 代 J a v a - N o w J a v a . c o m*/

public class Main {


  public void main(String[] argv) {

    // Get a byte array

    byte[] bytes = new byte[] { (byte) 0x12, (byte) 0x0F, (byte) 0xF0 };


    // Create a BigInteger using the byte array

    BigInteger bi = new BigInteger(bytes);


    // Format to binary

    String s = bi.toString(2); 


    // Format to octal

    s = bi.toString(8); 
    /** 
    来 自 
    时 代 J a v a 公 众 号 - nowjava.com
    **/


    // Format to decimal

    s = bi.toString();


    // Format to hexadecimal

    s = bi.toString(16); // 120ff0

    if (s.length() % 2 != 0) {

      // Pad with 0

      s = "0" + s;

    }


    // Parse binary string

    bi = new BigInteger("100101110111111110000", 2);

    System.out.println(bi);

    

    // Parse octal string

    bi = new BigInteger("7760", 8);

    System.out.println(bi);

    

    // Parse decimal string

    bi = new BigInteger(
展开阅读全文