Number literal and representation

来源:互联网 发布:文学cms 编辑:程序博客网 时间:2024/04/29 07:00

http://blogs.msdn.com/allen/archive/2008/01/31/number-value-and-representation.aspx

Here’s a function to show the hexadecimal literal of an integer number:

string get_hex(int val) {
    const char* hex = "0123456789ABCDEF";
    int type_len = 2 * sizeof(int);
    unsigned char mask = 0xF;
    string s("");

    for(int i=type_len-1; i>=0; --i) {
        s += hex[(val >> (i * 4)) & mask];
    }

    return s;
}


Here’s another function to show the binary representation in memory in terms of hexadecimal:

string hex_in_mem(int &val) {
    string s("");
    const char* hex = "0123456789ABCDEF";
    unsigned char mask = 0xF;
    unsigned char* byte_pointer = reinterpret_cast<unsigned char*>(&val);

    for(int i=0; i!=sizeof(int); ++i) {
        s += hex[((*(byte_pointer+i)) >> 4) & mask];
        s += hex[(*(byte_pointer+i)) & mask];
    }

    return s;
}


On my environment which is x86/Vista/gcc they are different. Take integer
12345678 for an instance:
Its hexadecimal literal is:
00 BC 61 4E
Well the representation in memory is:
4E 61 BC 00

Yes, binary representation in memory may be different with its binary literal and it’s environment dependent. That actually is something regarding big/little endian and is the contract between operating system and physical box, and, more important, is transparent to end programmers

原创粉丝点击