从reinterpret_cast获取原始char *值

时间:2017-12-12 09:59:07

标签: c++ casting reinterpret-cast

请考虑以下代码:

const char* cTitle = "MyTitle";
__int64 i = reinterpret_cast<__int64>(ctitle);

每次运行此代码时,我都会获得i的不同值。 现在我想写一个测试来检查我们是否发送了正确的标题,所以我使用以下代码来实现目标但无法使用reinterpret_cast获得标题:

char* cOrgValue = reinterpret_cast<char*> (i);

甚至可以获得原始标题值,如果是,那么这是正确的方法吗?

修改

所以让我重新解释一下这个问题: 在使用reinterpret_cast将其转换为char*之后,如何获得__int64的原始值。

1 个答案:

答案 0 :(得分:2)

Don't use reinterpret_cast。这是我的建议。相反,请致电std::memcpy

const char cTitle[] = "MyTitle";
std::uint64_t i64 = 0;
static_assert(sizeof(cTitle) >= sizeof(i64), "wrong sizes");
std::memcpy(&i64, cTitle, sizeof(i64));

通过对memcpy的反向调用获得原始值。

注意:我使用了char数组而不是char指针,以便sizeof(cTitle)成为8(相关部分:{的数量读取字符串中的{1}},包括最终的char)。使用\0时,const char*将为sizeof(cTitle),这是未指定的。

相关问题