存储在unsigned char数组中

时间:2010-03-13 09:28:27

标签: c

我有一个关于unsigned char数组的问题。 如何连续在数组中存储整数?

例如,我需要先将01011存储到数组中。然后我需要存储101,如何在阵列中存储为01011101? 谢谢你的帮助!

3 个答案:

答案 0 :(得分:0)

首先存储01011。您将获得值00001011.然后,当您想要存储三个位时,执行左移三个位置(您将获得01011000)并使用00000101进行OR,您将获得01011101.但是,这样做你这样做必须要确定你在第一次分配后只填充了五位。

答案 1 :(得分:0)

显然,您需要在数组增长时调整其大小。动态内存分配/重新分配可能是一种方法。注意选择正确的重新分配策略。

除此之外,如果您不仅限于C,您可能需要查看C ++ STL容器。

答案 2 :(得分:0)

为此,您应该编写一个名为bitstream的抽象数据类型。它可以有以下界面:

这是文件bitstream.h

#ifndef BITSTREAM_H
#define BITSTREAM_H

typedef struct bitstream_impl bitstream;
struct bitstream_impl;

/**
 * Creates a bit stream and allocates memory for it. Later, that memory
 * must be freed by calling bitstream_free().
 */
extern bitstream *bitstream_new();

/**
 * Writes the lower 'bits' bits from the 'value' into the stream, starting with
 * the least significand bit ("little endian").
 *
 * Returns nonzero if the writing was successful, and zero if the writing failed.
 */
extern int bitstream_writebits_le(bitstream *bs, unsigned int value, unsigned int bits);

/**
 * Writes the lower 'bits' bits from the 'value' into the stream, starting with
 * the most significand bit ("big endian").
 *
 * Returns nonzero if the writing was successful, and zero if the writing failed.
 */
extern int bitstream_writebits_be(bitstream *bs, unsigned int value, unsigned int bits);

/**
 * Returns a pointer to the buffer of the bitstream.
 *
 * The returned pointer remains valid until the next time that one of the
 * bitstream_write* functions is called. The returned buffer must not be
 * modified. All bits in the buffer that have not yet been written are zero.
 * (This applies only to the last byte of the buffer.) Each byte of the buffer
 * contains at most 8 bits of data, even if CHAR_BITS is larger.
 */
extern unsigned char *bitstream_getbuffer(const bitstream *bs);

/**
 * Returns the number of bits that have been written to the stream so far.
 */
extern unsigned int bitstream_getsize(const bitstream *bs);

/**
 * Frees all the memory that is associated with this bitstream.
 */
extern void bitstream_free(bitstream *bs);

#endif

然后你需要为这个接口编写一个实现。它应该位于名为bitstream.c的文件中。这是一个练习。

使用比特流应该非常简单:

#include "bitstream.h"

static void
die(const char *msg) {
    perror(msg);
    exit(EXIT_FAILURE);
}

int main(void)
{
    bitstream *bs;
    unsigned char *buf;

    bs = bitstream_new();
    if (bs == NULL)
        die("bitstream_new");

    if (!bitstream_writebits_be(bs, 0x000b, 5))
        die("write 5 bits");

    if (!bitstream_writebits_be(bs, 0x0005, 3))
        die("write 3 bits");

    if (bitstream_getsize(bs) != 8)
        die("FAIL: didn't write exactly 8 bits.");

    buf = bitstream_getbuffer(bs);
    if (buf[0] != 0x005dU)
        die("FAIL: didn't write the expected bits.");

    bitstream_free(bs);
    return 0;
}