簡體   English   中英

將 uint8_t 數組轉換為字符串

[英]convert uint8_t array to string

我的項目我有一個結構,它有一個unsigned int arrayuint8_t )類型的成員,如下所示

typedef uint8_t  U8;
typedef struct {
    /* other members */
    U8 Data[8];
} Frame;

收到一個指向Frame類型變量的指針,在調試期間我在 VS2017 的控制台中看到它如下

/* the function signatur */
void converter(Frame* frm){...}

frm->Data   0x20f1feb0 "6þx}\x1òà...   unsigned char[8] // in debug console

現在我想將它分配給一個 8 字節的字符串

我像下面那樣做,但它連接數組的數值並產生類似"541951901201251242224"

std::string temp;
for (unsigned char i : frm->Data)
{
    temp += std::to_string(i);
}

也試過const std::string temp(reinterpret_cast<char*>(frm->Data, 8)); 拋出異常

在你原來的演員const std::string temp(reinterpret_cast<char*>(frm->Data, 8)); 您將右括號放在錯誤的位置,因此它最終會執行reinterpret_cast<char*>(8) ,這就是崩潰的原因。

使固定:

std::string temp(reinterpret_cast<char const*>(frm->Data), sizeof frm->Data);

只需離開std::to_string 它將數值轉換為其字符串表示形式。 因此,即使您給它一個char ,它也會將其轉換為整數並將其轉換為該整數的數字表示形式。 另一方面,只需使用+=char添加到std::string 嘗試這個:

int main() {
    typedef uint8_t  U8;
    U8 Data[] = { 0x48, 0x65, 0x6C, 0x6C, 0x6F };
        std::string temp;
        for (unsigned char i : Data)
        {
            temp += i;
        }
        std::cout << temp << std::endl;
}

有關std::string+=運算符的更多信息和示例,請參見此處

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM