Установка бита четности в программе передачи

Я пишу программу, которая имитирует передачу символов по сети. Я написал следующую функцию:

int getCharBit(char c, int bitNum){
    return (c & (1 <<bitNum)) >> bitNum; 
}


// returns the ith bit of the character c
int getShortBit(short num, int bitNum)
{
    return (num & (1 <<bitNum)) >> bitNum;
}


// sets bit i in num to 1
int setShortBit(int bitNum, short *num){
   return  num | (1 << bitNum);
}


// count the number of bits in the short and returns the number of bits

/* input:
   num - an integer

Output:
the number of bits in num

*/

int countBits(short num)

{

   int sum=0;
   int i;
   for(i = num; i != 0; i = i >> 1){
      sum += i & 1;
   }      
   return sum;

}

Я также написал функцию, которая подсчитывает количество единиц в коротком целом числе и маску:

int countOnes(short int num, short int pMask){
   short tempBit = num & pMask;
   sum = 0;
   while(tempBit > 0){
      if((tempBit & 1) == 1){
         sum ++;
      }
      tempBit >> 1;
   }
   return sum;
}

и функция, которая устанавливает бит четности:

int setParityBits(short *num)
    // set parity bit p1 using mask P1_MASK by
    // get the number of bits in *num and the mask P1_MASK
    int numOnes = countOnes(num, P1_MASK);
    // if the number of bits is odd then set the corresponding parity bit to 1  (even parity)
if ((numOnes % 2) != 0){
   setShortBit(1, num);
}
    // do the same for parity bits in positions 2,4,8

int numOnes2 = countOnes(num, P2_MASK);
if ((numOnes2 % 2) != 0){
   setShortBit(2, num);
}
int numOnes4 = countOnes(num, P4_MASK);
if ((numOnes4 % 2) != 0){
   setShortBit(4, num);
}
int numOnes8 = countOnes(num, P8_MASK);
if ((numOnes8 % 2) != 0){
   setShortBit(8, num);
}

Мне также дают несколько функций, которые должны читать ввод и передавать его. Проблема в одной из функций, которые я написал.

Например, если я запускаю программу и набираю hello в качестве входных данных, я должен получить 3220 3160 3264 3264 7420 в качестве выходных данных, но я получаю 0 0 0 0 0.

Кажется, я не могу понять, что я делаю неправильно. Может ли кто-нибудь помочь мне?

0 ответов

Другие вопросы по тегам