Java Reference
In-Depth Information
type? Or conversely, what if we want to map the bits of a floating-point value into
an integer type?
In Chapter 9 we used methods in the DataInputStream wrapper to read
values from a byte array source as a particular primitive type. However, for a data
set that is a mix of many types, it might be convenient to read the data into a single
array of an integer type. You can then convert those elements of the array that
represent float values with the intBitsToFloat() method in the Float
class. There are also methods to map from float to int .
The Float class includes:
static int floatToIntBits (float x) - Returns an int type whose bits
match those of a float according to the IEEE 754 floating-point “single format” bit
layout as described in Appendix 3.
static int floatToRawIntBits (float value) - This is the same as
floatToInBits (float x) except the NaN value can be other than the single
IEEE 754 official value ( 0x7fc00000 ). As explained in Appendix 3, a value is NaN if
all the bits in the exponent equal 1 and any of the bits in the significand equal 1.
static float intBitsToFloat (int x) -Treats the bits in the x value as the
bits in a float value and returns it as a float type. That is, this method converts the
output of floatToIntBits (float) back to a float value.
The Double class has a corresponding set of methods for converting back and
forth from long and double types.
The Integer wrapper also offers some bit handling methods:
static String toBinaryString (int i) - Converts the value i to a string
with 0 and 1 characters but no leading zeros.
static int parseInt (String s, int radix) - Conversely, if s is a string
representing a binary value, such as “110103,” and radix is set to 2, then the method
returns an int value equal to the binary value. (We previously used parseInt
(String s) ,which assumes a decimal value is represented by string.)
The Long wrapper has two methods with similar names for converting long
values to binary strings and converting strings that represent binary values to
long values.
As discussed in Section 10.13, the BigInteger class contains bitwise meth-
ods to test bits, shift bits, clear a particular bit, and so forth. However, remember
that any change of a bit results in a new BigInteger object since instances of
this class are immutable.
10.15 Other utilities
There are a number of other utility classes in the java.util package. The
class Stack , for example, provides a last-in-first-out type vector with pop and
push methods. We discussed the Formatter class in Chapter 5 that deals with
Search WWH ::




Custom Search