打印char甚至奇偶校验

时间:2012-03-09 23:37:04

标签: c

这可能是一个愚蠢的问题,但我似乎无法解决这个问题。

我编写了一个以char作为输入的程序,输出char及其十六进制值然后检查偶校验并将奇偶校验位设置为1并再次输出“new”char和它的十六进制值。然而,使用printf和%c似乎不是要走的路,我不明白为什么或如何修复它,所以如果有人能解释为什么不能以及我应该做什么,我将非常感激。哦,随意评论我正在学习的代码,所以批评总是好的:)

int checkParity(unsigned char myChar); //returns 0 if even 1 if odd

int main()  {
  int i;
  unsigned char input;

  printf("Enter char: ");
  scanf("%c", &input);

  /* print unchanged char and hex with */
  printf("c7: %c ", input);
  printf("hex: %x \n", input);

  /*if parity is odd*/
  if(checkParity(input)){
    /*change to even*/
    input = (input|0x80);
  }

  /* print char and hex even parity */
  printf("c8: %c ", input);
  printf("hex: %x \n", input);  

  return 0;
}

int checkParity(unsigned char myChar){
  int i;
  int parity = 0;

  while(myChar){    //while myChar != 0
    parity += (myChar&1);   //add result of myChar AND 1 to parity
    myChar = myChar>>1;     //shift bits left by 1
  }
  //printf("parity equals: %d\n", parity);
  if(parity%2){ // if odd parity
    return 1;
  }
  else { //even parity
    return 0;
  }
}

1 个答案:

答案 0 :(得分:4)

什么是奇偶校验位?

奇偶校验位是一种可以使用的简单形式的错误检查,例如,当您将数据从一台机器传输到另一台机器时。如果两台机器都达成一致,比如偶数奇偶校验,那么接收器就会知道具有偶校验的任何传入字符都是错误接收的。但是,任何类型的奇偶校验只能识别奇数个错误位:单个字符中的两个错误将相互抵消,并且得到的奇偶校验将是正确的。此外,接收器无法确定哪个位(或位)不正确;奇偶校验提供错误 detection ,但不提供错误 correction

应如何处理收到的数据?

接收方应计算并验证每个传入字符的奇偶校验。如果它检测到具有无效奇偶校验的字符,则应以某种方式指示错误。在最好的情况下,它可能会要求发射机重新发送角色。

一旦验证了字符,接收方必须剥离奇偶校验位,然后再打开字符进行进一步处理。这是因为,由于奇偶校验位用于错误检测,因此它从数据有效载荷中“丢失”。因此,启用奇偶校验将可用数据值的数量减少一半。例如,8位可以具有256个可能值(0-255)中的一个。如果一位用于奇偶校验,则只剩下7位来编码数据,只留下128个有效值。


由于您要求评论/批评,这里是您的代码的修订版评论版本:

#include <stdio.h>

// Consider using a boolean data type, as the function returns
// "true" or "false" rather than an arbitrary integer.
int isOddParity(unsigned char myChar);


int main(void) {
  unsigned char input;

  printf("Enter char: ");
  scanf("%c", &input);

  // Force even parity by setting MSB if the parity is odd.
  unsigned char even = isOddParity(input) ? input | 0x80 : input;

  // Print the original char, original hex, and even-parity hex
  // Print hex values as 0xHH, zero-padding if necessary.  This program
  // will probably never print hex values less than 0x10, but zero-padding
  // is good practice.
  printf("orig char: %c\n", input);
  printf("orig  hex: 0x%02x\n", input);
  printf("even  hex: 0x%02x\n", even);
  return 0;
}

// Calculate the parity of myChar.
// Returns 1 if odd, 0 if even.
int isOddParity(unsigned char myChar) {
  int parity = 0;

  // Clear the parity bit from myChar, then calculate the parity of
  // the remaining bits, starting with the rightmost, by toggling
  // the parity for each '1' bit.
  for (myChar &= ~0x80;  myChar != 0;  myChar >>= 1) {
    parity ^= (myChar & 1);   // Toggle parity on each '1' bit.
  }
  return parity;
}