簡體   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