Java Reference
In-Depth Information
represent the character '
A'
because (
0041)
16
is the hexadecimal representation
of the integer (65)
10
that represents the character
A
, but in the computer, this is
maintained as the binary integer (
1000001)
2
.
Maintaining the binary representation in an array
When we keep the binary representation of a nonnegative integer
n
in an
array
d
with the minimum number of elements, we place bit
d
0
in element
d[0]
,
d
1
in
d[1]
, and so on. Thus, we can write:
n =
∑
i in 0..d.length-1
d[i]*2
i
This means that if
n=0
, the array has
0
elements —yes, in Java, you can
create an array with
0
elements. If
n=8
, array
d
is
{0
,
0
,
0
,
1}
—our conventional
way of writing the array puts the least significant bit first, so we have to look at
the array in reverse to see it as a binary integer:
1000
.
Converting an integer to base 2
Suppose
int
variable
n
contains a non-negative integer. We write a function
that produces the binary representation of
n
in an array
d
of exactly the right
length. Thus, each bit
d
i
shown above will be in array element
d[i]
. We inves-
tigate how to calculate the bits of the binary representation of
n>0
, where:
n = d
k-1
*2
k-1
+ ... + d
1
*2
1
+ d
0
*2
0
From this formula, we see that:
n%2 = d
0
/** =
an array
d[0..]
that contains exactly the binary representation of
n
(n ≥ 0)
*/
public static int
[] IntToBinary(
int
n) {
int
[] d=
new int
[32];
int
x= 0;
int
k= 0;
// inv:
the binary representation of
n
is:
//
the binary representation of
x
followed by the reverse of
b[0..k-1]
while
(x != 0) {
d[k]= x % 2;
x= x / 2;
k= k + 1;
}
int
[] dc=
new int
[k];
System.arraycopy(d, 0, dc, 0, k);
return
dc;
}
Figure 1II.2:
Function
IntToBinary
Search WWH ::
Custom Search