2010-03-13 66 views
-2

我有一個關於unsigned char數組的問題。 我怎樣才能不斷地在數組中存儲一個整數?存儲在unsigned char數組中

例如,我需要先將01011存儲到數組中。那麼我需要存儲101,我怎樣才能在數組中存儲爲01011101? 感謝您的幫助!

+0

太模糊 - 說明您認爲該數組的內容是以後的 - 舉個具體的例子。可能還需要功課標籤? –

+0

數組長度有限。你能否更詳細地解釋一下。 – dirkgently

+0

什麼是01011和0101101?基地8? (如果是這樣,他們太大的數字存儲在一個無符號的字符)基地2?和101?基地10?他們代表人物?請提供更多細節。 –

回答

0

首先存儲01011。您將獲得值00001011.然後,當您要存儲三個位時,執行左移三個位置(您將獲得01011000)並與00000101進行或運算,您將得到01011101。但是,以這種方式執行此操作必須明確地知道你在第一次任務後只填滿了五位。

0

很明顯,你需要調整數組的大小。動態內存分配/重新分配是一種可行的方法。注意選擇正確的重新分配策略。

除此之外,你可能想看看C++ STL容器,如果你不僅限於C.

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; 
} 
相關問題