JDK-6322074 : Converting integers to string as if unsigned
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.lang
  • Affected Version: 6
  • Priority: P3
  • Status: Closed
  • Resolution: Fixed
  • OS: generic
  • CPU: generic
  • Submitted: 2005-09-09
  • Updated: 2013-12-20
  • Resolved: 2012-05-07
The Version table provides details related to the release that this issue/RFE will be addressed.

Unresolved : Release in which this issue/RFE will be addressed.
Resolved: Release in which this issue/RFE has been resolved.
Fixed : Release in which this issue/RFE has been fixed. The release containing this fix may be available for download as an Early Access Release or a General Availability Release.

To download the current JDK release, click here.
JDK 8
8 b25Fixed
Related Reports
Relates :  
Relates :  
Description
Josh writes:

Today a colleague of mine needed to translate a long to a string as if
it were unsigned.  java.lang.Long lets you do this in binary, octal,
or hex, but not decimal.  I had to give him this piece of inefficient
code that leverages BigIntegers string conversion capabilities:

  public static String ulongToString(long i) {
    BigInteger b = BigInteger.valueOf(i & Long.MAX_VALUE);
    if (i < 0)
      b = b.flipBit(Long.SIZE - 1);
    return b.toString();
  }

Surely we don't want people doing this!  As we've discussed over the
years, Integer, Long, and Short should have a bunch of methods for
dealing with integeral primitives as if they were unsigned.  We don't
need many.  If we could only have one, it would be the one above
(coded efficiently, of course).  But I think we should also have some
upconversion operations (ushort -> int, uint -> long), arithmetic
operations (most but not all of which are simple pass-throughs to the
signed operations), and comparison operations  (which rely on the ^
MAX_VALUE trick).  Can we please have these in Dolphin?  I am willing
to write them.

Comments
PUBLIC COMMENTS See See http://hg.openjdk.java.net/jdk8/tl/jdk/rev/71200c517524
21-01-2012

SUGGESTED FIX See 4504839.
21-01-2012

EVALUATION This capability should be included when unsigned library support is added to the platform.
09-11-2005

WORK AROUND Since the Java language does have unsigned division by powers of 2, if you want to divide a negative long by 10 as if it were an unsigned value, you can divide by 2, yielding a positive long, then divide by 5. Combined with the fact that subtraction and multiplication are both bitwise identical for signed and unsigned, that gives this method... public static String unsignedLongToString(long x) { if (x >= 0) return Long.toString(x); long quot = (x >>> 1) / 5; long rem = x - quot * 10; return Long.toString(quot) + rem; } ...which is about 2.5 times faster than using BigInteger.
10-09-2005