[英]Converting from unsigned Char* to unsigned int
When I do the following, I get this error: 当我执行以下操作时,出现此错误:
../src/Sample.cpp:19: error: cast from \‘UINT8*\’ to \‘UINT8\’ loses precision
../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;
}
How would I go about solving this. 我将如何解决这个问题。 Keep in mind I am not trying to convert string to unsigned long, rather converting char* (the ADDRESS value ) to int.
请记住,我不是在尝试将字符串转换为unsigned long,而是将char *(ADDRESS值)转换为int。
Thanks 谢谢
Solution: 解:
Turns out that this problem has to do with the pointer size. 原来,这个问题与指针大小有关。 On a 32 bit machine, the pointer size is 32 bit, and for 64 bit machine is of course 64. The above wont work on a 64 bit machine, but will on a 32 bit machine.
在32位计算机上,指针大小为32位,而对于64位计算机,指针大小当然为64。以上内容在64位计算机上不起作用,但在32位计算机上有效。 This will work on a 64 bit machine.
这将在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;
}
Assuming that sizeof(int) == sizeof(void*) you can use this code to convert: 假设sizeof(int)== sizeof(void *),则可以使用以下代码进行转换:
int b = *reinterpret_cast<int*>(&a);
or variations thereof. 或其变体。 I think static_cast will work too.
我认为static_cast也可以使用。
Of course a has to be l-value (able to be assigned to) to get the address of it. 当然,a必须是l值(可以分配给它)才能获取其地址。 For non-l-values, you need to use a function and the good old union trick will work:
对于非l值,您需要使用一个函数,好的旧联合技巧将起作用:
int Pointer2Int (void* p)
{
union { void* p; int i; } converter;
converter.p = p;
return converter.i;
}
This isn't a good idea, but the line should read: 这不是一个好主意,但该行应显示为:
UINT32 b = reinterpret_cast<UINT32>(a);
reinterpret_cast
takes the type of the destination type as the template parameter. reinterpret_cast
将目标类型的类型作为模板参数。
With the correct type g++ will tell you that it isn't a good idea: 使用正确的类型,g ++会告诉您这不是一个好主意:
error: invalid cast from type ‘char’ to type ‘int’
see Cthutu's answer for a more correct approach. 有关更正确的方法,请参阅Cthutu的答案。
An option would be to : 一种选择是:
int *a; int * a; char b[64];
字符b [64]; int c;
int c;
a = (int*) malloc (sizeof(int)); 一个=(int *)malloc(sizeof(int));
sprintf(b, "%d", a); sprintf(b,“%d”,a);
c = atoi(b); c = atoi(b);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.