美剧《硅谷》第三季第一集神秘代码写的是什么?

from https://www.zhihu.com/question/44606486

Image for post
Image for post

试了一下,运行结果如红框所示,第一反应是HBO的编剧也是蛮拼的。。。

这是一段花式输出字符串的程序,源代码被黑科技玩坏了

原理其实很简单,我们注意到代码中有个特别的 magic number 是65,没错,那就是ASCII 表里的 A,前面那一堆不过是在叠加偏移量,以此来实现输出。

具体地说,偏移量的计算是用 0x1FULL 这个无符号长整型常量作为掩码(二进制表示为 11111),从低位开始每次从

0x79481E6BBCC01223 + ((dcf_t)0x1222DC << 64)

这个大整数中取出 5 位,所取出的 5 位二进制表示即为偏移量。

我们用同样的 trick 可以输出任意想要的字符串。比如:

#include <stdio.h> 
#include <stdlib.h>

将得到:

I_LOVE_YOU

摸清了套路,我们也成了老司机,甚至可以写一段程序来生成这段看起来很黑科技的代码。
gen.c

#include <stdio.h> 
#include <string.h>

现在用这段程序,我们可以随意发挥了

Image for post
Image for post

代码如下
#include <stdio.h>
#include <stdlib.h>

typedef unsigned long u64;

/* Start here */
typedef void enc_cfg_t;
typedef int enc_cfg2_t;
typedef __int128_t dcf_t;

enc_cfg_t _ctx_iface(dcf_t s, enc_cfg2_t i){
int c = (((s & ((dcf_t)0x1FULL << i * 5)) >> i * 5) + 65);
printf(“%c”, c); }
enc_cfg2_t main() {
int i;
for (i=0; i<17; i++){
_ctx_iface(0x79481E6BBCC01223 + ((dcf_t)0x1222DC << 64), i);
}
printf(“n”);
}
/* End here */

//TOneverDO change name
u64 HammingCtr(u64 a, u64 b) {
u64 c = a ^ b;

/*for (d = 0; c>0; c >>= 1)
{
d += c & 1;
}*/
// O(m) lol no thanks

//1000 wrap into loop
c = c — ((c >> 1) & ~0UL/3);
c = (c & ~0UL/5) + ((c >> 2) & ~0UL/5);
c = (c & 0UL/0x21) + ((c >> 4) & 0UL/0x11);
c = (c & ~0UL/0x101) + ((c >> 8) & ~0UL/0x101);
c = (c & ~0UL/0x10001)+((c>>16)&~0UL/0x10001);
c = (c & ~0UL/0x100000001)+((c>>32)&~0UL/0x100000001);

//TODO throw away intermediates… but could be useful later (see seander)
return c;
}

//TODO transform + multiply spectra + transform back. faster? lossy?

u64 * ConvolutedMagic(u64 *x, u64 y, u64 *z, u64 n, u64 n_y) {
//z is array of offsets in BITS
//y is left-aligned of length n_y
//TODO function is ridic fragile. e.g. if len z > len x/y…

u64 * a = malloc(sizeof(u64)*n);
u64 b,o_64,o_bit;

int i;
for ( i=0; i<n; i++) {
o_64 = z[i] >> 6;
o_bit= z[i] — ((z[i]>>6) << 6);
b = *(x+o_64) << o_bit;
if (o_bit > 0) {
b += x[o_64+1] >> (64-o_bit);
}
b = (b >> (64-n_y))<<(64-n_y);
y = (y >> (64-n_y))<<(64-n_y); //not necessary, just in case
a[i] = HammingCtr(b,y);
}

return a;
}

/*
int main() {
//test hamconv
u64 x[] = {1,2,3,4,5,6,7,8};
u64 y = 15;
u64 z[] = {0,64,64*2,64*3,64*4,64*5,64*6,64*7};
u64 n_samples = sizeof(z)/sizeof(u64);
u64 *out = ConvolutedMagic(x,y,z,n_samples,64);
for (int i=0; i<n_samples;i++) {
}
return 0;
}
*/

Written by

自由撰稿人,时评人,平等公义追求者

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store