使用指针缩小C++中的类型转换

Joh*_*ate 0 c++ pointers type-conversion

我在C++中使用指针进行向下类型转换时遇到了一些问题,在我想出这样做之前,谷歌基本上告诉我这是不可能的,而且我从C++学到的任何书都没有涉及到.我认为这会起作用......

long int TheLong=723330;
int TheInt1=0;
int TheInt2=0;
long int * pTheLong1 = &TheLong;
long int * pTheLong2 = &TheLong + 0x4;

TheInt1 = *pTheLong1;
TheInt2 = *pTheLong2;

cout << "The double is " << TheLong << " which is "
     << TheInt1 << " * " << TheInt2 << "\n";
Run Code Online (Sandbox Code Playgroud)

第五行的增量可能不正确,但输出让我担心我使用gcc 3.4.2的C编译器会自动将TheInt1转换为long int或其他东西.输出看起来像这样......

双倍是723330,即723330*4067360

TheInt1的输出不可能高,并且没有TheInt2的输出.

我有三个问题......

我是否走在正确的轨道上?

第五行的适当增量是多少?

为什么地狱是TheInt1/TheInt2允许如此大的价值?

Mag*_*off 5

int 可能是32位,这使它的范围为-2*10 ^ 9到2*10 ^ 9.

在行中,long int * pTheLong2 = &TheLong + 0x4;你正在对a进行指针运算long int*,这意味着地址将增加0x4 long ints 的大小.我想你假设它long int的大小是它的两倍int.这绝对不能保证,但如果您在64位模式下进行编译,可能也是如此.因此,您希望将指定大小的一半long int(正好是int您假设的大小)添加到指针中.int * pTheLong2 = (int*)(&TheLong) + 1;实现了这一点.

您正走在正确的轨道上,但请记住,正如其他人所指出的那样,您现在正在探索未定义的行为.这意味着可移植性被破坏,优化标志可能会很好地改变行为.


顺便说一句,输出更正确的东西(假设机器是小端)将是:

cout << "The long is " << TheLong << " which is "
     << TheInt1 << " + " << TheInt2 << " * 2^32" << endl;
Run Code Online (Sandbox Code Playgroud)

为了完整起见,一个明确定义的32位整数转换为两个16位整数:

#include <cstdint>
#include <iostream>

int main() {
    uint32_t fullInt = 723330;
    uint16_t lowBits  = (fullInt >>  0) & 0x0000FFFF;
    uint16_t highBits = (fullInt >> 16) & 0x0000FFFF;

    std::cout << fullInt << " = "
        << lowBits << " + " << highBits << " * 2^16"
        << std::endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出: 723330 = 2434 + 11 * 2^16