簡體   English   中英

C ++,將std :: string轉換為uint8_t

[英]c++, convert std::string to uint8_t

在我正在使用的c ++解決方案中,我有一個返回字符串引用的函數。 const std::string& getData() const {return mData;} ,而mData是std::string mData; 現在我想將其轉換為uint8_t數組,以將其傳遞給另一個函數指針。

/* in another header -> typedef uint8_t  U8; */
const std::string& d = frame.getData();
U8 char_array[d.length()];
/* here I want to put the d char by char in char_array*/

不推薦使用strcpy ,因此我正在使用strcpy_sstrcpy_s(char_array, d);

我當然會得到哪種couldn't match type char(&)[_size] against unsigned char[]

而且將static或重新解釋為char*強制轉換也不起作用。

使用向量,您正在編寫的是VLA,這不是有效的C ++( U8 char_array[d.length()] )。 然后使用std::copy

const std::string& d = frame.getData();
std::vector<U8> char_array(d.length() + 1, 0);

問題是,是否需要字符串\\0的結尾,因此如果要最后一個\\0 ,它將為d.length()+ 1。 然后:

std::copy(std::begin(d), std::end(d), std::begin(char_array));

更新:顯然,目標是將此向量存儲在另一個uint8_t[8] ,如果它是一個名為foo的變量,請執行以下操作:

std::copy(std::begin(d), std::end(d), std::begin(foo));

但是請先檢查長度...並通過結構填充作為參考。 還可以獲得一本不錯的C ++書。

更新:由於從您的評論看來,您具有一個編譯時常數最大大小,因此我添加了一個真實的數組版本:

#include <string>
#include <vector>
#include <cstdint>
#include <algorithm>
#include <iterator>
#include <array>

struct foo {
    std::string& getData() {return mData;}
    const std::string& getData() const  {return mData;}
    std::vector<uint8_t> get_array() const {
        std::vector<uint8_t> array;
        std::copy(mData.cbegin(), mData.cend(), std::back_inserter(array));
        return array;
    };

    static constexpr size_t max_size = 8u;
    std::array<uint8_t, max_size> get_max_array() const {
        std::array<uint8_t, max_size> array;
        std::copy_n(mData.cbegin(), max_size, array.begin());
        return array;
    }

private:
    std::string mData;
};

暫無
暫無

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

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