How does this print “hello world”?

后端 未结 9 1334
Happy的楠姐
Happy的楠姐 2021-01-29 17:33

I discovered this oddity:

for (long l = 4946144450195624l; l > 0; l >>= 5)
    System.out.print((char) (((l & 31 | 64) % 95) + 32));
9条回答
  •  说谎
    说谎 (楼主)
    2021-01-29 18:16

    You've encoded characters as 5-bit values and packed 11 of them into a 64 bit long.

    (packedValues >> 5*i) & 31 is the i-th encoded value with a range 0-31.

    The hard part, as you say, is encoding the space. The lower case english letters occupy the contiguous range 97-122 in Unicode (and ascii, and most other encodings), but the space is 32.

    To overcome this, you used some arithmetic. ((x+64)%95)+32 is almost the same as x + 96 (note how bitwise OR is equivalent to addition, in this case), but when x=31, we get 32.

提交回复
热议问题