获取整数我有一个vector<char>
,我希望能够从矢量中的一系列位中获取无符号整数。例如。从位内'std :: vector'
而且我似乎无法能够写入正确的操作,以获得所需的输出。我的意图的算法是这样的:
&
与(0xff >> unused bits in byte on the left)
<<
结果的第一个字节左输出字节数*位的字节|
这与最终的输出数- 对于每个后续字节:
<<
左边是(字节宽度 - 索引)*每个字节的位数|
该字节与最终输出>>
最终输出
|
最后一个字节(不移动)由未使用的位的数目的最终输出在字节右边
这里是我的编码它的企图,不给出正确的结果:
#include <vector>
#include <iostream>
#include <cstdint>
#include <bitset>
template<class byte_type = char>
class BitValues {
private:
std::vector<byte_type> bytes;
public:
static const auto bits_per_byte = 8;
BitValues(std::vector<byte_type> bytes) : bytes(bytes) {
}
template<class return_type>
return_type get_bits(int start, int end) {
auto byte_start = (start - (start % bits_per_byte))/bits_per_byte;
auto byte_end = (end - (end % bits_per_byte))/bits_per_byte;
auto byte_width = byte_end - byte_start;
return_type value = 0;
unsigned char first = bytes[byte_start];
first &= (0xff >> start % 8);
return_type first_wide = first;
first_wide <<= byte_width;
value |= first_wide;
for(auto byte_i = byte_start + 1; byte_i <= byte_end; byte_i++) {
auto byte_offset = (byte_width - byte_i) * bits_per_byte;
unsigned char next_thin = bytes[byte_i];
return_type next_byte = next_thin;
next_byte <<= byte_offset;
value |= next_byte;
}
value >>= (((byte_end + 1) * bits_per_byte) - end) % bits_per_byte;
return value;
}
};
int main() {
BitValues<char> bits(std::vector<char>({'\x78', '\xDA', '\x05', '\x5F', '\x8A', '\xF1', '\x0F', '\xA0'}));
std::cout << bits.get_bits<unsigned>(15, 29) << "\n";
return 0;
}
(作用:http://coliru.stacked-crooked.com/a/261d32875fcf2dc0)
我似乎无法将我的头围绕在这些位操作上,而且我发现调试非常困难!如果任何人都可以更正上面的代码,或者以任何方式帮助我,那将非常感谢!
编辑:
- 我的字节长
- 返回可以是8,16,32或64位wside
- 整数被存储在大端排序的整数8个比特
这对于无符号整数很有用,谢谢!我只是在调查有符号整数的那一刻 - 我并不完全确定我的'get_bits(14,22)'所需的输出是否是最新的!我会很快回来,并有一个更新,或者如果我发现这是所需的行为,为你打勾标记:) –
Ell
看起来这个代码不适用于'bits.get_bits(0,32) ;' - 它返回零而不是预期的'519053860746' –
Ell
你是对的。这个错误是由于结果被掩盖的方式。左移将位移出重要性,导致位掩码为0.我已经添加了一个修复程序。 – Cookyt