简体   繁体   中英

Binary and Hex negative numbers in Java

I have this program to print out a number in any base but I'm just wondering how I can make it print negative numbers in say binary or hex. The method is called printInt and it just returns 0 when I try to print a negative number in binary and it throws a StringIndexOutOfBoundsException exception for hex input. Here is the code:

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);
    }
}

Add an if statement in your printInt method to take care of a negative number:

//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)));
}

Sample session with this change:

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

Corner case: This will not work with the number -9 223 372 036 854 775 808, the minimal long value, because a long cannot hold the corresponding positive value. I think the correct solution is input validation. For example, require that long values are in the range -1 000 000 000 000 000 000 through 1 000 000 000 000 000 000 and bases are within 2 through 16.

Be simple!

public static void printInt(long n, int base) {
    System.out.println((n < 0 ? "-" : "") + Long.toUnsignedString(Math.abs(n), base));
}

Pay attention, like formally there's no eg negative binary or hex numbers. They are written in special form. But in this case you have to know the size of variable.


A would recommend not to use System.out.println() . It's is better to build and return a string and then, client could could print it.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM