Java Reference
In-Depth Information
static String toAlignedBinaryString(int i, int numBits)
{
String result = Integer.toBinaryString(i);
if (result.length() > numBits)
return null; // cannot fit result into numBits
columns
int numLeadingZeros = numBits-result.length();
String zerosPrefix = "";
for (int j = 0; j < numLeadingZeros; j++)
zerosPrefix += "0";
return zerosPrefix+result;
}
}
The
toAlignedBinaryString()
method takes two arguments: the first argu-
ment specifies the 32-bit integer that is to be converted into a binary string, and the
second argument specifies the number of bit columns in which to fit the string.
After calling
toBinaryString()
to return
i
's equivalent binary string without
leading zeros,
toAlignedBinaryString()
verifies that the string's digits can fit
into the number of bit columns specified by
numBits
. If they do not fit, this method
returnsnull.(Youwilllearnabout
length()
andother
String
methodslaterinthis
chapter.)
Movingon,
toAlignedBinaryString()
calculatesthenumberofleading
"0"
s
toprependto
result
,andthenusesaforlooptocreateastringofleadingzeros.This
method ends by returning the leading zeros string prepended to the result string.
Althoughusingthecompoundstringconcatenationwithassignmentoperator(
+=
)in
alooptobuildastringlooksokay,itisveryinefficientbecauseintermediate
String
objectsarecreatedandthrownaway.However,Iemployedthisinefficientcodesothat
I can contrast it with the more efficient code that I present later in this chapter.
When you run this application, it generates the following output:
00000111
0000000011111111
null