获取字节流(1 和 0)并将它们存储在 uint8_t 数组中



我正在尝试获取这个字节信息流(1和0(,并尝试将其存储在uint8_t数组中(每个索引都是一个字节长的8位(。我很难理解如何将8位存储到给定位图大小的1个索引位置(对于本例为4(。

因此,我们将有一个大小为4的uint8_t数组,其输出如下所示:

数组输出-->111111 00 00011110 00001111 01

任何帮助都将不胜感激!!非常感谢。

int allocatedMem[26] = { 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1 };
int bitmapSize = 0;

for (int i = 0; i < sizeof(allocatedMem) / sizeof(allocatedMem[0]); i +=8)
{
bitmapSize++;
}
cout << "Size of bitmap: " << bitmapSize << endl;

在独立环境中用数据分配和初始化位图的一些代码+malloc/free/assert:

#include <cstddef>  // size_t
#include <cstdint>  // uint8_t
#include <climits>  // CHAR_BIT
#include <cassert>  // assert
#include <cstring>  // malloc / free
#include <iostream> // for output only
#include <bitset>   // for output only
// variable sized arrays in structs are only defined in C
extern "C" {
struct Bitmap {
using word = uint8_t;
static constexpr size_t wordsize = sizeof(word) * CHAR_BIT;
size_t size;
word map[];
};
}
using Bitmap = struct Bitmap;
// Cpp Core Guidelines violation:
// don't return ownership as pointer
// don't take array+size separately
Bitmap * alloc_init_bitmap(int allocated[], size_t n) {    
// calculate bitmap size without risk of overflow
const size_t bitmap_size = [](size_t n) {
size_t t = n / Bitmap::wordsize;
if (t * Bitmap::wordsize < n) ++t;
return t;
}(n);
// allocate Bitmap
const size_t total_size = offsetof(Bitmap, map) + bitmap_size;
Bitmap *bitmap = (Bitmap*)malloc(total_size);
assert(bitmap != nullptr);
bitmap->size = n;
// initialize bits
Bitmap::word t = 0;
Bitmap::word *pos = bitmap->map;
Bitmap::word bit = 1;
while (n-- > 0) {
// add bit by bit from allocated to t
t = t | bit * (*allocated++ != 0);
bit <<= 1;
if (bit == 0) {
// all bits in t have been set, store word
*pos++ = t;
t = 0;
bit = 1;
}
}
// store partial word if allocatedMem isn't multiple of words
if (bitmap->size % Bitmap::wordsize != 0) *pos = t;
return bitmap;
}
int main() {
int allocatedMem[26] = { 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1 };
Bitmap *bitmap = alloc_init_bitmap(allocatedMem, sizeof(allocatedMem) / sizeof(allocatedMem[0]));
std::cout << "Bitmap of size " << bitmap->size << ":n";
for (size_t i = 0; i < bitmap->size / Bitmap::wordsize; ++i) {
std::cout << " " << std::bitset<8>(bitmap->map[i]);
}
std::cout << std::endl;
free(bitmap);
}

演示

std::bitset的使用纯粹是为了输出映射。malloc/free必须用自己的方式来替换,为位图获取一些内存。如果位图是用来管理内存的,这就有点恶性循环了。

输出看起来与allocatedMem不同,因为每个字的输出都是右边的位0和左边的位7。

最新更新