[英]Binary and Hex negative numbers in Java
我有這個程序可以打印任何基數的數字,但是我只是想知道如何使它以二進制或十六進制的形式顯示負數。 該方法稱為printInt
,當我嘗試以二進制形式打印負數時,它僅返回0,並為十六進制輸入拋出StringIndexOutOfBoundsException
異常。 這是代碼:
import java.util.Scanner;
public class Nums {
public static final String DIGIT_TABLE = "0123456789abcdef";
//prints nums in any base
public static void printInt(long n, int base){
if(n >= base){
printInt(n / base, base);
}
System.out.print(DIGIT_TABLE.charAt((int) (n % base)));
}
//prints n in decimal form
/*public static void printDecimal(long n){
if(n >= 10){
printDecimal(n / 10);
}
System.out.print((char) ('0' + (n%10)) + " ");
}*/
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter 5 numbers in the following order: 1 long value to see it in decimal form, a long value and a int for the base "
+ "to be represented in and a long and a base for another number ");
long input1 = s.nextLong();
long input2 = s.nextLong();
int input3 = s.nextInt();
long in4 = s.nextLong();
int in5 = s.nextInt();
System.out.println("Prints number in decimal form");
//printDecimal(input1);
System.out.println();
System.out.println("Prints number in binary: ");
printInt(input2, input3);
System.out.println();
System.out.println("Number in hex");
printInt(in4, in5);
}
}
在您的printInt
方法中添加一個if
語句來處理負數:
//prints nums in any base
public static void printInt(long n, int base) {
if (n < 0) {
System.out.print('-');
n = -n;
}
if (n >= base) {
printInt(n / base, base);
}
System.out.print(DIGIT_TABLE.charAt((int) (n % base)));
}
帶有此更改的示例會話:
Enter 5 numbers in the following order: 1 long value to see it in decimal form, a long value and a int for the base to be represented in and a long and a base for another number
-314
-314
2
-314
16
Prints number in decimal form
Prints number in binary:
-100111010
Number in hex
-13a
極端情況:這不適用於最小的long值-9 223 372 036 854 775 808,因為long
無法容納相應的正值。 我認為正確的解決方案是輸入驗證。 例如,要求long值的范圍是-1 000000000000000000000到1000000000000000000,基數必須在2到16之間。
很簡單!
public static void printInt(long n, int base) {
System.out.println((n < 0 ? "-" : "") + Long.toUnsignedString(Math.abs(n), base));
}
注意,像形式上一樣,沒有負數或十六進制數。 它們以特殊形式編寫。 但是在這種情況下,您必須知道變量的大小。
A建議不要使用System.out.println()
。 最好構建並返回一個string
,然后客戶端可以打印它。
public static String convert(long val, int radix) {
String str = Long.toUnsignedString(Math.abs(val), radix);
if (radix == 2)
str = "0b" + str;
else if (radix == 8)
str = '0' + str;
else if (radix == 16)
str = "0x" + str;
return val < 0 ? '-' + str : str;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.