Java’s BigInteger is a very handle tool to have in your toolbox as a ColdFusion programmer. If you’re ever in a situation where you need to do operations on large numbers (larger than a mere 32-bit Integer can handle) you’ll need to delve into BigInteger territory.
For example, someone came into the #Coldfusion channel on freenode.net wanting to know why InputBaseN("0x85A308d3", 16) was giving a negative response. Well, that’s because most numeric operations in ColdFusion are performed on Integers, and the argument was sufficiently large enough to overflow the result into negative.
BigInteger to the rescue! Feast on this code:
<cfset bigint = createObject("java", "java.math.BigInteger").init("85A308d3", 16).toString(10)/>Very simply, we’re creating a BigInteger with the value of 85A308D3 in hexadecimal (the 16 is called the radix) and then outputting it via toString(10) where the 10 is the radix for decimal.
Simple! And if you look at the Javadocs for BigInteger, you’ll see you can perform a whole slew of operations: addition, subtraction, modulo, xor, and, or, pow… almost any numeric operation.
So that’s 10 posts. Time for a celebratory bourbon.
FYI, we use BigInteger in Mach-II to do timestamps (in ms) for the timespan cache strategy.
BigInteger is a great thing. Thanks Mike for posting about it.