JDK-4172595 : No way to determine # of bits in basic types
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.lang
  • Affected Version: 1.2.0
  • Priority: P5
  • Status: Closed
  • Resolution: Duplicate
  • OS: generic
  • CPU: generic
  • Submitted: 1998-09-10
  • Updated: 1999-05-20
  • Resolved: 1999-05-20
Related Reports
Duplicate :  
Description

Name: clC74495			Date: 09/10/98


There seems to be no predefined constants in Java for determining the number of bits
in various integral types. For instance, in C, I can #include <limits.h> and then use
constants such as CHAR_BITS to indicate the number of bits in a 'char' value. In Java,
I have to define my own local constant do do something similar, and my own local
constant will almost certainly have a different name from the one used by other Java
developers. Or, I can just hardcode the number, which usually leads to
difficult-to-understand code.

I would like to see constants added to each of the numeric 'wrapper' classes, like so:

class Integer
{
   ...
   public static final BITS = 32;
}
class Byte
{
   public static final int BITS = 8;
}
etc. for classes Long, Short and Char.

This would allow easy writing of code such as:
byte [] bytes = whatever;
int getBitAt(int bitIndex)
{
    return ((bytes[bitIndex / Byte.BITS] 
             >> (bitIndex % Byte.BITS)) & 1;
}
rather than encouraging people to write code such as:
int getBitAt(int index)
{
    return (data[x / 8] >> (x % 8)) & 1;
}

As a somewhat seperate issue, it seems to me that this information would also
be useful as a virtual method inherited from class Number.
(Review ID: 38581)
======================================================================

Comments
WORK AROUND Name: clC74495 Date: 09/10/98 Declare one's own constants to echo information that should be common to all Java virtual machines. ======================================================================
2004-06-11

EVALUATION It would be convenient to have these constants predefined, but their values are fixed by the language specification, so it is not so essential that implementations provide way to query them. In C, limits.h plays a more important role, as portable code cannot assume that contains the same definitions across implementations. This would be a nice clean-up for a future overhaul of the language, but none is planned at present. william.maddox@Eng 1998-09-21
1998-09-21