United StatesChange Country, Oracle Worldwide Web Sites Communities I am a... I want to...
JDK-6322074 : Converting integers to string as if unsigned

Details
Type:
Enhancement
Submit Date:
2005-09-09
Status:
Closed
Updated Date:
2013-12-20
Project Name:
JDK
Resolved Date:
2012-05-07
Component:
core-libs
OS:
generic
Sub-Component:
java.lang
CPU:
generic
Priority:
P3
Resolution:
Fixed
Affected Versions:
6
Fixed Versions:

Related Reports
Relates:
Relates:

Sub Tasks

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
                                     
2012-01-21
SUGGESTED FIX

See 4504839.
                                     
2012-01-21
EVALUATION

This capability should be included when unsigned library support is added to the platform.
                                     
2005-11-09
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.
                                     
2005-09-10



Hardware and Software, Engineered to Work Together