Why this apparently "random" numbers print "Java is Awesome"

Viewed 335

How does this program print "Java is Awesome"?

String s = IntStream.of(1635148106, 544434464, 1936029505, 6647151)
                    .flatMap(e -> IntStream.range(0, 4).map(i -> e >> i * 8))
                    .mapToObj(i -> Character.toString((byte) i))
                    .collect(Collectors.joining());
System.out.println(s);
2 Answers

A little help for you:

01001010 01100001 01110110 01100001 (avaJ)
00100000 01101001 01110011 00100000 ( si )
01000001 01110111 01100101 01110011 (sewA)
01101111 01101101 01100101           (emo)

Now read it backwards:

01100001 01110110 01100001 01001010
00100000 01110011 01101001 00100000
01110011 01100101 01110111 01000001
00000000 01100101 01101101 01101111

Which is nothing but:

1247901281
543781664
1098343795
1869440256

The IntStream.of(1635148106, 544434464, 1936029505, 6647151) creates a stream of 4 elements. Then, for each of those elements, we will do

e -> IntStream.range(0, 4).map(i -> e >> i * 8)

which basically creates 4 elements resulting from the operations

e >> 0
e >> 8
e >> 16
e >> 24

So, the entire operation e -> IntStream.range(0, 4).map(i -> e >> i * 8) on the elements IntStream.of(1635148106, 544434464, 1936029505, 6647151) results in:

1635148106 6387297 24950 97
544434464  2126697 8307  32
1936029505 7562615 29541 115
6647151    25965   101   0

The flatMap(...) part converts the previous operation to an IntStream.

Then in the next operation:

mapToObj(i -> Character.toString((byte) i))

first (byte) i is applied therefore:

1635148106 6387297 24950 97
544434464  2126697 8307  32
1936029505 7562615 29541 115
6647151    25965   101   0

becomes:

74 97 118 97
32 105 115 32
65 119 101 115
111 109 101 0

which if you look at the ASCII table:

enter image description here

corresponds to :

JAVA
<space>is<space>
Awes
ome<null>

The remaining operations:

.mapToObj(i -> Character.toString((byte) i))
    .collect(Collectors.joining());

just convert it to a String representation.

For those wondering how from

1635148106 6387297 24950 97
544434464  2126697 8307  32
1936029505 7562615 29541 115
6647151    25965   101   0

you get:

74 97 118 97
32 105 115 32
65 119 101 115
111 109 101 0

First, convert the first elements into binary, and since one byte is 8 bits, extract the last 8 bits of that binary, and convert the same back to decimal. For instance:

1635148106

in binary is

1100001011101100110000101001010

The last 8 bits:

01001010

in decimal is 74.

Or convert into hexadecimal 1635148106 -> 6176614A exact relevant part (the byte) -> 4A and look directly into the ASCII table -> J.

Related