首页 > 解决方案 > c++ 将四个 unsined char 转换为一个 unsigned int

问题描述

在我的 c++ 程序中,我有一个包含四个unsigned char成员的结构

struct msg
{
    unsigned char zero; unsigned char one; unsigned char two; unsigned char three;
}

并创建了一个结构数组

msg myMsg[4] = {{0x11,0x22,0xAA,0xCC},{...},{...},{...}};

现在在一个函数中,我想将此数组的索引作为unsigned int

unsigned int procMsg(int n){
  return myMsg[n]; // of course this is worng
}

像这样的值:0xCCAA2211

标签: c++casting

解决方案


考虑一下:

像这样的消息:{0x01, 0x01, 0x01, 0x01}可以解析为

00000001 00000001 00000001 00000001(bin) = 16.843.009(dec)

所以你只需要获取每个字符并根据其位置移动它们,即

char0 完全没有移动,

char1 向左移动 8 个位置(或乘以 2^8)

char2 向左移动 16 个位置(或乘以 2^(8*2))

char3 向左移动 24 个位置(或乘以 2^(8*3))

unsigned int procMsg(Message &x)
{
    return (x.three << 24) |
           (x.two << 16) |
           (x.one << 8) |
           x.zero;
}

int main(int argc, char *argv[])
{
                         //0     1     2     3
    Message myMsg[4] = {{0x01, 0x01, 0x01, 0x01},  //00000001 00000001 00000001 00000001 = 16.843.009
                        {0xFF, 0x00, 0xAA, 0xCC},  //00000001 00000001 00000001 00000001 = 3.433.693.439
                        {0x01, 0x00, 0x00, 0x00},  //00000001 00000001 00000001 00000001 = 1
                        {0x00, 0x00, 0x00, 0x00}   //00000000 00000000 00000000 00000000 = 0
                       };

    for (int i = 0; i<4; i++)
    {
        Message x = myMsg[i];
        std::cout << "res: " << procMsg(myMsg[i]) << std::endl;
    }

    return  0;

}

推荐阅读