用字符数组存int

EUYUIL告诉我可以用字符数组存int。挺好玩。

unsigned char test[100];
memset(test, 0, sizeof(test));
int a = 2147483647;
int *p = (int*)&test;
*p = a;
int b = *p;
cout << b << endl;

此时test数组为{255, 255, 255, 127, 0…}
当然,如果a是1的话,test就是{1, 0, 0, 0, 0…}
这是VS2010编译的结果。。不知道其他编译器其他平台结果怎么样。。

刚刚在stackoverflow搜到这个问题,以后有空再看看吧。

总感觉我C++好弱,指针几乎没用过= =

Update @ 2011/12/13 23:39
如果放入TCHAR里,就是{65535, 32767, …}。

2 thoughts on “用字符数组存int

  1. 呵呵,发现有提到我……

    这个似乎有的是从低位存到高位,有的是反过来的。比如 Java 似乎是反的,它在读取二进制文件的时候就是反的,写项目的时候就以为它也是从低位到高位存,所以就搞错了。

    听说 Intel 的处理器还是什么的比较喜欢这样搞,具体忘了。

    还有 TCHAR 的定义是这样的:如果你定义了 UNICODE 那么 TCHAR 就是 wchar_t, 如果你没有定义的话就是 char. 如果你用 VS 2010 来弄的话,默认是定义了 UNICODE 的。

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">