我需要解壓二進制文件。由於二進制文件編碼爲14位,我必須讀取14位而不是8位來解碼。但據我所知,使用getc()
來讀取文件只給我8位每次。有沒有任何有效的方法來實現這一目標?下面是可以完成這項工作的代碼塊,但它看起來效率不高,我該如何改進它?如何一次讀取二進制文件14位,而不是8位?
unsigned int input_code(FILE *input)
{
unsigned int return_value;
static int input_bit_count=0;
static unsigned long input_bit_buffer=0L;
while (input_bit_count <= 24)
{
input_bit_buffer |=
(unsigned long) getc(input) << (24-input_bit_count);
input_bit_count += 8;
}
return_value=input_bit_buffer >> (32-BITS);
input_bit_buffer <<= BITS;
input_bit_count -= BITS;
return(return_value);
}
謝謝Alexey。就像你說的那樣,我無法找到一種優雅的方式來優化這段代碼。而對於EOF問題,由於文件末尾是特別編碼的,輸入將在讀取特殊代碼時結束。 – Tony 2013-03-22 23:30:19
優雅的方法是*不*逐字節讀取,而是讀取更大的塊並處理它們。提示:什麼是'8 * 14'? – 2013-03-22 23:31:38
@NikBougalis可能。但是我們對這個問題一無所知,有多少數據被讀取,處理它花了多少時間,所以爲什麼事先優化呢? – 2013-03-22 23:33:46