// following code prints out Letters aA bB cC dD eE ....
class UpCase {
public static void main(String args[]) {
char ch;
for(int i = 0; i < 10; i++) {
ch = (ch
UpCase
The decimal number 66503
represented by a 32 bit signed integer is 00000000 00000001 00000011 11000111
in binary.
The ASCII letter a
represented by a 8 bit char is 01100001
in binary (97 in decimal).
Casting the char to a 32 bit signed integer gives 00000000 00000000 00000000 01100001
.
&
ing the two integers together gives:
00000000 00000000 00000000 01100001
00000000 00000001 00000011 11000111
===================================
00000000 00000000 00000000 01000001
which casted back to char gives 01000001
, which is decimal 65, which is the ASCII letter A
.
Showbits
No idea why you think that 128
, 64
and 32
are all 10000000
. They obviously can't be the same number, since they are, well, different numbers. 10000000
is 128
in decimal.
What the for loop does is start at 128
and go through every consecutive next smallest power of 2: 64
, 32
, 16
, 8
, 4
, 2
and 1
.
These are the following binary numbers:
128: 10000000
64: 01000000
32: 00100000
16: 00010000
8: 00001000
4: 00000100
2: 00000010
1: 00000001
So in each loop it &
s the given value together with each of these numbers, printing "0 "
when the result is 0
, and "1 "
otherwise.
Example:
val
is 123
, which is 01111011
.
So the loop will look like this:
128: 10000000 & 01111011 = 00000000 -> prints "0 "
64: 01000000 & 01111011 = 01000000 -> prints "1 "
32: 00100000 & 01111011 = 00100000 -> prints "1 "
16: 00010000 & 01111011 = 00010000 -> prints "1 "
8: 00001000 & 01111011 = 00001000 -> prints "1 "
4: 00000100 & 01111011 = 00000000 -> prints "0 "
2: 00000010 & 01111011 = 00000010 -> prints "1 "
1: 00000001 & 01111011 = 00000001 -> prints "1 "
Thus the final output is "0 1 1 1 1 0 1 1"
, which is exactly right.