简体   繁体   English

从 char 向量转换为 short 向量和 float 向量

[英]converting from a vector of char to a vector of short and a vector of float

I have written this program to convert from a char to a short:我编写了这个程序来将字符转换为短字符:

typedef unsigned char u8;
typedef unsigned short u16;

u16 combine2bytes(u8 a, u8 b) {
    return b | (a << 8);
}


int main()
{
    std::vector<char> cVec{ 'a','r','t','u' };
    std::vector<short>sVec;
    for (auto i = 0; i < cVec.size(); i+=2)
    {
        sVec.push_back(combine2bytes(cVec.at(i),cVec.at(i+1)));
    }
    std::cout << sVec.size() << '\n';
    for (auto i = 0; i < sVec.size(); i++)
        std::cout << sVec.at(i) << '\n';
    return 0;
}

So if I understand, if we have a vector (or an array) of 1 byte data and I want to create a 2-byte vector from that 1-byte vector, I have to read 2 bytes from that 1-byte vector?因此,如果我理解,如果我们有一个 1 字节数据的向量(或数组)并且我想从该 1 字节向量创建一个 2 字节向量,我必须从该 1 字节向量中读取 2 个字节? Is this correct?这个对吗? same goes to float and int; float 和 int 也是如此; we have to read 4 consecutive bytes?我们必须读取 4 个连续的字节?

but if I have to read from file, suppose this is the file:但如果我必须从文件中读取,假设这是文件:

F0 5A 6B A9 4C E3 etc..

suppose now that I want to cast it to short, so I have to take: F0 and 5A but which one is the LSB and MSB (NB: the structure is little Endian)?假设现在我想将其转换为短,所以我必须采用: F0 and 5A但哪一个是 LSB 和 MSB(注意:结构是小端序)?

And if I have to cast it to a float: how I can cast it so I can get floating point?如果我必须将其转换为浮点数:如何转换它以便获得浮点数? because if I will cast it to a float, it's similar as I cast it to int?因为如果我将它转换为浮点数,它与我将它转换为 int 类似吗? how to get the floating point?如何获得浮点数?

Thanks in advance提前致谢

The famous answer it depends fits here.著名的答案取决于这里。

  1. MSB/LSB : It depends on how you stored those bytes, for example if you store the MSB in vector case 0 then when reading you should consider this. MSB/LSB :这取决于您如何存储这些字节,例如,如果您将 MSB 存储在向量 case 0 中,那么在阅读时您应该考虑这一点。 You can not guess if you do not have this information.如果您没有此信息,您无法猜测。

  2. data type : It depends on what the data you stored there.数据类型:这取决于您存储在那里的数据。 For example if it's a float then just do the bit shifing and then cast, you can try that by a concrete example.例如,如果它是一个浮点数,那么只需进行位移位然后进行转换,您可以通过一个具体示例进行尝试。 However, if it's another program who has written those bytes or they're not written on the same architecture, then you should have a protocol that defines which bytes are for the mantissa.但是,如果是另一个程序编写了这些字节,或者它们不是在同一架构上编写的,那么您应该有一个协议来定义哪些字节用于尾数。 again you can not guess if you do not have this information.再次,如果您没有此信息,您将无法猜测。

  3. you code snippet: you should cast the data to short before bit-shifting and ORing it to ensure these operations are performed on 16-bits not on 8-bits data:您的代码片段:您应该在移位和 ORing 之前将数据转换为短格式,以确保这些操作是在 16 位而不是 8 位数据上执行的:

     u16 combine2bytes(u8 a, u8 b) { return ((u16)b) | (((u16)a) << 8); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM