繁体   English   中英

从unsigned Char *转换为unsigned int

[英]Converting from unsigned Char* to unsigned int

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

../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;
}

我将如何解决这个问题。 请记住,我不是在尝试将字符串转换为unsigned long,而是将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值(可以分配给它)才能获取其地址。 对于非l值,您需要使用一个函数,好的旧联合技巧将起作用:

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

这不是一个好主意,但该行应显示为:

UINT32 b = reinterpret_cast<UINT32>(a);

reinterpret_cast将目标类型的类型作为模板参数。

使用正确的类型,g ++会告诉您这不是一个好主意:

error: invalid cast from type ‘char’ to type ‘int’

有关更正确的方法,请参阅Cthutu的答案。

一种选择是:

int * a; 字符b [64]; int c;

一个=(int *)malloc(sizeof(int));

sprintf(b,“%d”,a);

c = atoi(b);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM