so true

心怀未来,开创未来!
随笔 - 160, 文章 - 0, 评论 - 40, 引用 - 0
数据加载中……

字节序,终于搞得比较透了

#include <iostream>
#include <string.h>
#include <stdio.h>
#include <string>
#include <vector>
#include <map>
#include <set>

using namespace std;

int main(int argc, char* argv[])
{
    const int i = 0x61626364;
    printf("%x\n", *(char*)&i); //这里显示64,因为little endian的原因,little代表LSB,endian代表变量所存放的内存的起始端,即内存的低地址
    printf("%x\n", i);//61626364

    const char* pp = "abcd"; //这在内存里从低地址到高地址依次存的真的是abcd,而之前定义的int i,在内存里从低地址到高地址依次存的却是dcba
    printf("%x\n", *(int*)pp);//64636261

    wchar_t a=L'我';//wchar_t其实就是unsigned long, 注意,这里必须加前缀L,加L代表该字符是UNICODE,否则编译会报warning(gcc会认为这样的写法和'abc'一样邪恶), 这里的赋值其实就相当于unsigned long a = 0x6211
    printf("%x\n", a);//6211
    printf("%x\n", *(char*)&a);//这里显示11,因为我的UNICODE编码是6211
    cout << sizeof(a) << endl; // 4

    //const char* pW = L"我"; 编译会报错,因该用const wchar_t* pW = L"我";

    const char* p = "我"; //这个char序列存放的依次是e6, 88, 91, 我的utf8编码是e68891,这是因为当前使用的编辑器vi设定了utf8编码
    cout << strlen(p) << endl; //3
    printf("%x++\n", p[0]); //e6
    printf("%x\n", *(int*)p);//最终显示为9188e6, %x代表将一个int的数值以十六进制的形式显示出来,由于little endian的原因,在提取一个int的时候,会从内存的开始连续取4个btype,并且将最后一个byte最为int的MSB(即LSB放在前内存前端,MSB放在内存后端)

    const char* p2 = "abcd";
    printf("%x\n", *(int*)p2); //dcba

    return 0;
}

posted on 2011-04-08 10:19 so true 阅读(398) 评论(0)  编辑  收藏 所属分类: C&C++


只有注册用户登录后才能发表评论。


网站导航: