簡體   English   中英

將typedef short轉換為vector(char)

[英]Convert typedef short to vector (char)

我是C ++的新手。 有誰知道如何將typedef short轉換為vector(char)? 將解壓縮轉換為vector(char)。

opusencoder encodedatag;
opus_int16 *decompress = encodedatag.encodedata(...);

我假設您有一個short並且想要將其表示為vector<char>char序列。

如果是這樣,那是我的建議,並通過一個簡單的測試:)

#include <iostream>
#include <vector>
#include <algorithm>

using opus_int16 = short;

std::vector<char> toVector(opus_int16 arg)
{
    std::vector<char>   converted;
    opus_int16          remainder(0);
    bool                isNegative((arg < 0) ? true : false);

    if (isNegative)
        arg = -arg;

    while (arg != 0)
    {
        remainder = arg % 10;
        arg /= 10;
        converted.push_back(remainder + 48);
    }


    if (isNegative)
        converted.push_back('-');

    std::reverse(converted.begin(), converted.end());

    return converted;
}

int main(int argc, char **argv)
{
    opus_int16 example = -156;

    std::vector<char> test(toVector(example));

    for (auto i : test)
        std::cout << i;

    std::cin.get();

    return 0;
}

假設收到的短褲在主機的字節序中,並且該短褲實際上是16位(uint16_t會更好),並且char是該短褲的大端字節表示形式,則可以將短褲轉換為char可以這樣進行:

std::pair<uint8_t, uint8_t> convert_uint16_to_uint8s(uint16_t in)
{
    std::pair<uint8_t, uint8_t> out;
    out.first = in >> 8;
    out.second = in & 0xff;
    return out;
}

如果知道數組的長度(由decompress指向),則可以遍歷數組並轉換每個short和push_back每個char。

std::vector<uint8_t> output;
for (int i = 0; i < decompress_length; ++i)
{
    std::pair<uint8_t, uint8_t> chars = convert_uint16_to_uint8s(decompress[i];
    output.push_back(chars.first);
    output.push_back(chars.second);
}

(例如,未經編譯或測試的代碼)

暫無
暫無

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

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