2013-04-18 19 views
1

我在計算如何將9個char放入c編程中的4個unsigned short數組中遇到問題。把7個字符放入2個無符號短short的數組中

我知道char是1個字節,但只有7位被使用,因爲ascii表是0〜127,所以我需要7 * 9 = 63位。由於每個short是2個字節,所以每個short有16個位。 4短陣列是4 * 16 = 64位。這意味着我能適應那些9焦炭引入的陣列4無符號短

所以基本上我有

無符號短* PTR,theArray [4],信= 0;

int mask;

//讀取字符9,並把它保存到數組

我不明白的是如何讀取輸入4個字符,並保存到theArray。限制是我不能把它們放到一個字符串中,除了int外,我不能聲明任何東西。我知道我必須做一些操作,但我不知道如何閱讀輸入。感謝您的幫助!

+0

現在4或2無符號短褲?另外,你不能對'char'和'short'的字節大小做出假設。最後,你有什麼嘗試? – 2013-04-18 20:14:18

+1

你想從哪裏獲得輸入?一份文件?標準輸入? –

+1

使用int64_t代替4個短褲陣列可能會更容易 – kbickar

回答

0

這是輪班和/或操作員進場的地方。

我不能給出任何確切的例子,但你可以一起使用它們將字符「粉碎」成無符號短褲數組。

一個簡單的例子,你看可能不完全是什麼,應該是:

char j = 'J'; 
char y = 'Y'; 
unsigned short s = (y << 7) | j; 
+0

嗨,謝謝你的回覆。我知道我需要做轉換和所有這些東西,但我不知道如何讀取7個標準輸入字符,並將它放到該短陣列中,而不使用字符串或字符。不允許聲明。 – DumbProgrammer

0

如果我們可以假設無符號短= 16位和焦炭= 8,然後 除非我已經做出了錯字這是怎麼回事:

#include <stdio.h> 

int main() 
{ 
    unsigned short *ptr, theArray[4], letter = 0; 
    int mask; 

    // theArray: 
    // |<-------0------>|<-------1------>|<-------2------>|<-------3------>| 
    // characters: 
    // 0111111122222223 3333334444444555 5555666666677777 7788888889999999 

    // Because we use |= first clear the whole thing 
    theArray[0] = theArray[1] = theArray[2] = theArray[3] = 0; 

    /* char 1 */ letter=getchar(); 
       theArray[0] |= 0x7F00 & (letter << 8); 

    /* char 2 */ letter=getchar(); 
       theArray[0] |= 0x00FE & (letter << 1); 

    /* char 3 */ letter=getchar(); 
       theArray[0] |= 0x0001 & (letter >> 6); 
       theArray[1] |= 0xFC00 & (letter << 10); 

    /* char 4 */ letter=getchar(); 
       theArray[1] |= 0x03F8 & (letter << 3); 

    /* char 5 */ letter=getchar(); 
       theArray[1] |= 0x0007 & (letter >> 4); 
       theArray[2] |= 0xF000 & (letter << 12); 

    /* char 6 */ letter=getchar(); 
       theArray[2] |= 0x0FE0 & (letter << 5); 

    /* char 7 */ letter=getchar(); 
       theArray[2] |= 0x001F & (letter >> 2); 
       theArray[3] |= 0xC000 & (letter << 14); 

    /* char 8 */ letter=getchar(); 
       theArray[3] |= 0x3F80 & (letter << 7); 

    /* char 9 */ letter=getchar(); 
       theArray[3] |= 0x007F & letter; 

    return 0; 
} 
相關問題