1

I am writing a program that simulate a transmission of characters over the network. I have written the following function:

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;

}

I also written a function that counts the number of ones in a short integer num and a mask:

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;
}

and a function that sets the Parity Bit:

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);
}

I am also given a few function that are supposed to read the input and transmit it. The problem is in one of the functions I have written.

For example, if I run the program and type hello as an input, I should get 3220 3160 3264 3264 7420 as an output, but I get 0 0 0 0 0.

I can't seem to find what I was doing wrong, Could someone please help me?

user3055141
  • 109
  • 1
  • 2
  • 8
  • are you trying to set the parity bit for each byte of the input? are you trying to set even/odd/ or no parity? The max value of a byte is 255, so where does the (for instance) 3220 come from and what does it mean? – user3629249 Feb 01 '15 at 17:47
  • 1
    @user3629249 the 3220 3160 3264 3264 7420 comes from the test code my instructor provided. I am trying to set an even parity. I wasn't provided with a lot of instructions about this code. All the instructions I had are the comments in the code – user3055141 Feb 01 '15 at 18:24
  • Can you supply a little more info about the use of this? – wittrup Apr 04 '15 at 09:39

0 Answers0