interpret a negative number as unsigned with BigInteger java -


is possible parse negative number unsigned value java's biginteger?

so instance, i'd interpret -1 ffffffffffffffff.

is possible?

thanks

if thinking of two's complement, must specify working bit length. java long has 64 bits, biginteger not bounded.

you this:

// two's complement reference: 2^n .  // in case, 2^64 (so emulate unsigned long) private static final biginteger two_compl_ref = biginteger.one.shiftleft(64);  public static biginteger parsebigintegerpositive(string num) {     biginteger b = new biginteger(num);     if (b.compareto(biginteger.zero) < 0)         b = b.add(two_compl_ref);     return b; }  public static void main(string[] args) {     system.out.println(parsebigintegerpositive("-1").tostring(16)); } 

but implicitly mean working bigintegers in 0 - 2^64-1 range.

or, more general:

public static biginteger parsebigintegerpositive(string num,int bitlen) {     biginteger b = new biginteger(num);     if (b.compareto(biginteger.zero) < 0)         b = b.add(biginteger.one.shiftleft(bitlen));     return b; } 

to make more fooproof, add checks, eg

public static biginteger parsebigintegerpositive(string num, int bitlen) {     if (bitlen < 1)         throw new runtimeexception("bad bit length:" + bitlen);     biginteger bref = biginteger.one.shiftleft(bitlen);     biginteger b = new biginteger(num);     if (b.compareto(biginteger.zero) < 0)         b = b.add(bref);     if (b.compareto(bref) >= 0 || b.compareto(biginteger.zero) < 0 )         throw new runtimeexception("out of range: " + num);     return b; } 

Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -