C ++在两个字节上写一个数字

时间:2014-01-17 20:08:59

标签: c++

我是低级c ++的新手,我觉得有点难以理解如何操作位。我试图在我想要的压缩算法中使用以下内容:

unsigned int num = ...;//we want to store this number
unsigned int num_size = 3;//this is the maximum size of the number in bits, and
//can be anything from 1 bit to 32

unsigned int pos = 7;//the starting pos on the 1st bit.
//this can be anything from 1 to 8

char a;
char b;

如果num_size为3且pos为7,则我们必须将num存储在{的第7个第8个位{1}}以及a第一位。

2 个答案:

答案 0 :(得分:2)

怎么样?

a = num << (pos-1);
b = ((num << (pos-1)) & 0xFF00) >> 8;

只读

num = ((unsigned int)a + ((unsigned int b) << 8)) >> (pos - 1);

注意,这不会进行任何健全性检查,例如是否所有相关位都适合a和b,你必须自己做。

答案 1 :(得分:1)

对于此特定测试用例,适合2 unsigned char的最高数字实际为65535

#include <iostream>

unsigned char high(int input)
{
    return (input >> 8) & 0xFF;
}

unsigned char low(int input)
{
    return input & 0xFF;
}

int value(unsigned char low, unsigned char high)
{
    return low | (high << 8);
}

int main()
{
    int num = 65535;
    unsigned char l = low(num);
    unsigned char h = high(num);

    int val = value(l, h);
    std::cout<<"l: "<<l<<" h: "<<h<<"  val: "<<val;
}