簡體   English   中英

將大二進制字符串轉換為十六進制

[英]Converting a large binary string to hexadecimal

我有一個二進制字符串:

1010010111100101100010101010011011010001111100000010101000000000010000000111110111100"

如何將其轉換為十六進制字符串?

我嘗試使用包裝類LongInteger ,但它對我不起作用,拋出了NumberFormatException

你需要使用BigInteger - 數字太大而不適合原始值。 可以存儲在long的最大數字是9223372036854775807,而這個二進制字符串的十進制等效值要大得多,25069592479040759763832764。這就是你得到NumberFormatException的原因。

所以使用BigInteger

String s = "1010010111100101100010101010011011010001111100000010101000000000010000000111110111100";
BigInteger b = new BigInteger(s, 2);
System.out.println(b.toString(16));

...這使:

14bcb154da3e0540080fbc

由於二進制String的長度可能超過Integer或Long的容量,因此最好使用BigInteger。 請記住,在Java中,int總是32位,而長64位。

String binaryString = "1010010111100101100010101010011011010001111100000010101000000000010000000111110111100";
String hexString = new BigInteger(binaryString, 2).toString(16);
public static String convertBinaryToHex(String binInPut) {
    int chunkLength = binInPut.length() / 4, startIndex = 0, endIndex = 4;
    String chunkVal = null;
    for (int i = 0; i < chunkLength; i++) {
        chunkVal = binInPut.substring(startIndex, endIndex);
         System.out.println(Integer.toHexString(Integer.parseInt(chunkVal, 2)));
        startIndex = endIndex;
        endIndex = endIndex + 4;
    }

    return binInPut;

}

如果你使用大數字:

String hexString = new BigInteger(binaryString, 2).toString(16);

我用這個

fun String.binToHex(): String {
    val out = StringBuilder()
    val outArray = this.deviceInParts(4)
    outArray.forEach {
        if (it == "0000") out.append('0')
        if (it == "0001") out.append('1')
        if (it == "0010") out.append('2')
        if (it == "0011") out.append('3')
        if (it == "0100") out.append('4')
        if (it == "0101") out.append('5')
        if (it == "0110") out.append('6')
        if (it == "0111") out.append('7')
        if (it == "1000") out.append('8')
        if (it == "1001") out.append('9')
        if (it == "1010") out.append('A')
        if (it == "1011") out.append('B')
        if (it == "1100") out.append('C')
        if (it == "1101") out.append('D')
        if (it == "1110") out.append('E')
        if (it == "1111") out.append('F')
    }
    return out.toString()
}

fun String.deviceInParts(parts: Int): ArrayList<String> {
    val outArray = arrayListOf<String>()
    for (i in 0 until this.length step parts) {
        outArray.add(this.subString(i, parts))
    }
    return outArray
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM