【问题标题】:combining variables using bitwise operators使用按位运算符组合变量
【发布时间】:2012-02-23 07:40:26
【问题描述】:

我需要一个函数,它将四个 unsigned char 变量作为参数并将它们组合成一个 unsigned int。第一个 char 变量是 int 的第一个字节,第二个 char 是第二个字节,依此类推。这是我到目前为止所拥有的,它无法正常工作,在弄乱它并在谷歌上搜索了几个小时后,我无法弄清楚为什么。

uint32_t combineChar(unsigned char one, unsigned char two, unsigned char three, unsigned char four){

uint32_t com;

com = (uint32_t)one;

com = com << 8 | (uint32_t)two;

com = com << 8 | (uint32_t)three;

com = com << 8 | (uint32_t)four;

return com;       

}

【问题讨论】:

  • 您的代码结果与您的预期有何不同?

标签: c bit-manipulation


【解决方案1】:

您的代码是字节序依赖的。第一个字节(uint32_t)在某些系统中是最左边的,而在某些系统中是最右边的,因此您可能以与您想要的相反的方式存储字节。

(实际上,如果您只想要uint32_t,那很好。当您将它与char[4] 或类似的东西联合时,问题就开始了)

【讨论】:

    【解决方案2】:

    检查“

    uint32_t combineChar(unsigned char one, unsigned char two
                        , unsigned char three, unsigned char four){
    
       return one | (two << 8) | (three << 16) | (four <<24);
    
    }
    

    【讨论】:

    猜你喜欢
    • 2020-09-25
    • 2013-07-25
    • 2014-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-11
    • 1970-01-01
    相关资源
    最近更新 更多