Home > other >  I want to create a Java source that functions like TO_NUMBER of Oracle
I want to create a Java source that functions like TO_NUMBER of Oracle

Time:12-27

For example... Apply the hexadecimal "DE82C38142C69491" to Oracle TO_NUMBER The results are as follows.

select TO_NUMBER('DE82C38142C69491', 'XXXXXXXXXXXXXXXX') from dual

/* 
result : 
16033592583330894993 
*/

I tried this in Java and the code is as below.

Long.parseUnsignedLong("DE82C38142C69491", 16);

/*
result : 
-2413151490378656623
*/

I'm understanding something wrong. Is there a way to use Oracle's TO_NUMBER in Java?

CodePudding user response:

The hexadecimal number DE82C38142C69491 is -2413151490378656623.

Java longs are signed, and D has the top bit set, so DE82C38142C69491 represents a negative number.

Run System.out.println(Long.toHexString(-2413151490378656623L)); and you'll see you get DE82C38142C69491 back.

So you have all the bits of your original hex number.

You can use new BigInteger("DE82C38142C69491", 16); which will get you a BigInteger containing 16033592583330894993, but -2413151490378656623 already contains all your bits.

CodePudding user response:

Java's long is a signed 64-bit value with the range of -263 to 263-1. In Java 8, they've added some methods like for example Long.compareUnsigned(long x, long y), to allow unsigned handling of the same datatype, but all other methods will still treat them as signed. That's why:

System.out.println(Long.parseUnsignedLong("DE82C38142C69491", 16));

...which is effectively calling Long.toString(), will output

-2413151490378656623

But if you do:

System.out.println(Long.toUnsignedString(Long.parseUnsignedLong("DE82C38142C69491", 16)));

...you will get:

16033592583330894993

That's because 16033592583330894993 is actually smaller than 264-1 (the max. value of unsigned long). But if your numbers are so big, you're better off using something like BigInteger anyhow.

  • Related