所以我試圖翻轉長整數的位,這就是我正在做的事情,但我得到了 NumberFormatException。我將其轉換為 base-2 字串并在左側添加零以成為 32 字符,然后翻轉位,然后將其轉換回 base-10 的長整數。
Long n =4L;
String bits = String.format("2s", Long.toBinaryString(n)).replace(' ', '0');
bits = bits.replace("0", "3");
bits = bits.replace("1", "0");
bits = bits.replace("3", "1");
return Long.parseLong(bits.trim(), 10);
轉換為基數 2 后的 4L:
000000000000000000000000000000100
翻轉所有位后:,我得到了這個:
Exception in thread "main" java.lang.NumberFormatException: For input string: "11111111111111111111111111111011"
怎么了?我檢查了不可列印的字符但沒有,我還修剪了數字以防有任何多余的空格,我試圖在最后添加 L 但沒有任何效果,有什么問題?
uj5u.com熱心網友回復:
我不是 100% 確定這是否是您正在尋找的。這會將二進制字串轉換為長字串。注意:我沒有在方法中檢查 0。您可能需要更改它以滿足您的需要。
public long stringBinaryToLong( final String binaryString) {
if(binaryString == null) {
return 0l;
}
// Check length for long on binary string. How many binary digits are the max length.
// Determine this by taking log(base 2) for Long max.
// log base 2 not available so use this technique. --> log_base2 (x) = log_base10 (x) / log_base10 (2)
if( binaryString.length() > Math.ceil( Math.log10( (double) Long.MAX_VALUE ) / Math.log10( 2.0 ) ) ) {
throw new IllegalStateException("string of binary digits exceeds max size for a Java long.");
}
double base = 2.0, power=0.0;
long result = 0l;
for(int index=binaryString.length() - 1; index > -1; index--) {
if( binaryString.charAt(index) == '1') {
result = Math.pow(base, power);
}
power = 1.0;
}
return result;
}
uj5u.com熱心網友回復:
所以問題出在 parseLong 方法的基數引數上,基數是指定我要決議的字串的基數,而不是 parse 方法的輸出
所以整個問題通過替換這個來解決:
return Long.parseLong(bits.trim(), 10);
有了這個:
return Long.parseLong(bits.trim(), 2);
現在,位串(parseLong 方法的輸入)的基數為 2,如 radix 引數中所述
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/426255.html
上一篇:Python變數范圍-如果在內部例外中使用外部例外變數未定義
下一篇:如何檢測裝飾器中缺少的引數?
