[英]Put 7 char into an array of 2 unsigned short
我在弄清楚如何在C編程中將9個char放入4個unsigned short數組中時遇到麻煩。
我知道一個char是1個字節,但是僅使用7位,因為ascii表是0〜127,所以我需要7 * 9 = 63位。 由於short每個為2個字節,因此每個short有16位。 4 short的數組是4 * 16 = 64位。 這意味着我可以將這9個字符放入4個無符號的short數組中
所以基本上我有
無符號短* ptr,theArray [4],字母= 0;
整數掩碼
//讀取9個char並將其保存到數組
我不明白的是如何讀取4個字符的輸入並將其保存到theArray。 局限性是我不能先將它們放入字符串,除int之外不能聲明其他任何內容。 我知道我必須進行一些操作,但我只是不知道如何讀取輸入。 謝謝您的幫助!
這就是班次和/或操作員起作用的地方。
我無法提供確切的示例,但是您可以將它們一起使用,將字符“粉碎”成無符號短褲的數組。
一個簡單的示例(可能與您要找的不完全一樣)將是:
char j = 'J';
char y = 'Y';
unsigned short s = ( y << 7 ) | j;
如果我們可以假設unsigned short = 16位,而char = 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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.