[英]Convert typedef short to vector (char)
I am new at C++. 我是C ++的新手。 Does anyone know how to convert typedef short to vector(char) ?
有谁知道如何将typedef short转换为vector(char)? Convert decompress to vector (char) .
将解压缩转换为vector(char)。
opusencoder encodedatag;
opus_int16 *decompress = encodedatag.encodedata(...);
I presume you have a short
and you want to represent it as a sequence of char
s in a vector<char>
. 我假设您有一个
short
并且想要将其表示为vector<char>
的char
序列。
If that's the case, that's my suggestion, with a simple test :) 如果是这样,那是我的建议,并通过一个简单的测试:)
#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;
}
Assuming the received shorts are in the endianess of the host and that the short is actually 16 bits (uint16_t would be better) and the chars are expected to be the big endian representation of the shorts, converting shorts to char can be done like this: 假设收到的短裤在主机的字节序中,并且该短裤实际上是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;
}
If you know the length of the array, pointed to by decompress, you can iterate over the array and convert each short and push_back each char. 如果知道数组的长度(由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);
}
(code as example, not compiled or tested) (例如,未经编译或测试的代码)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.