gpt4 book ai didi

c++ - 从 unsigned Char* 转换为 unsigned int

转载 作者:行者123 更新时间:2023-11-27 23:24:45 27 4
gpt4 key购买 nike

当我执行以下操作时,出现此错误:

../src/Sample.cpp:19: 错误:从\u2018UINT8*\u2019 转换为\u2018UINT8\u2019 失去精度

#include <iostream>
using namespace std;

typedef unsigned char UINT8;
typedef unsigned int UINT32;

#define UNUSED(X) X=X

int main() {
UINT8 * a = new UINT8[34];
UINT32 b = reinterpret_cast<UINT8>(a);

UNUSED(b);

return 0;
}

我将如何解决这个问题。请记住,我不是要将字符串转换为无符号长整型,而是要将 char*(ADDRESS 值)转换为 int。

谢谢

解决方法:

原来这个问题与指针大小有关。在 32 位机器上,指针大小是 32 位,对于 64 位机器当然是 64。以上在 64 位机器上不起作用,但在 32 位机器上会。这将在 64 位机器上工作。

#include <iostream>
#include <stdint.h>

using namespace std;

typedef uint8_t UINT8;
typedef int64_t UINT32;

#define UNUSED(X) X=X

int main() {
UINT8 * a = new UINT8[34];
UINT32 b = reinterpret_cast<UINT32>(a);
UNUSED(b);

return 0;
}

最佳答案

假设 sizeof(int) == sizeof(void*) 你可以使用这段代码来转换:

int b = *reinterpret_cast<int*>(&a);

或其变体。我认为 static_cast 也可以。

当然,a 必须是左值(能够分配给)才能获得它的地址。对于非 l 值,您需要使用一个函数,并且好的旧 union 技巧将起作用:

int Pointer2Int (void* p)
{
union { void* p; int i; } converter;
converter.p = p;
return converter.i;
}

关于c++ - 从 unsigned Char* 转换为 unsigned int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10193675/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com