Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 views
in Technique[技术] by (71.8m points)

java - Any datatype for integers longer than a Long?

I want to convert binary to an integer, multiply it by 17, then convert it back to binary. This is my code:

Scanner scan = new Scanner(System.in);
String n = scan.nextLine();
long j = Long.parseLong(n, 2);
j = j * 17;
System.out.println(Long.toBinaryString(j));

I originally made j an int but changed it once I got a bigger test case:

10001111110001000101000001000100111100110101100011000011011001111000100110110000110101110101100001001100010111000101000100010010011000000010010

It had a NumberFormatException, which makes sense because longs can only store a limited amount of digits, so are there any datatypes for very long integers?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Did you tried BigInteger or BigDecimal.

https://www.baeldung.com/java-bigdecimal-biginteger

These two types are specifically meant for situations where numbers are required to have a large or arbitrary range like some value > or = to 1x10^307 and less than 1x10^-307

public void whenBigDecimalCreated_thenValueMatches() {
    BigDecimal bdFromString = new BigDecimal("0.1");
    BigDecimal bdFromCharArray = new BigDecimal(new char[] {'3','.','1','6','1','5'});
    BigDecimal bdlFromInt = new BigDecimal(42);
    BigDecimal bdFromLong = new BigDecimal(123412345678901L);
    BigInteger bigInteger = BigInteger.probablePrime(100, new Random());
    BigDecimal bdFromBigInteger = new BigDecimal(bigInteger);
        
    assertEquals("0.1",bdFromString.toString());
    assertEquals("3.1615",bdFromCharArray.toString());
    assertEquals("42",bdlFromInt.toString());
    assertEquals("123412345678901",bdFromLong.toString());
    assertEquals(bigInteger.toString(),bdFromBigInteger.toString());
}

That should help you .


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...