C 在传输程序中设置奇偶校验位
我正在写一个程序,模拟通过网络传输字符。 我编写了以下函数:C 在传输程序中设置奇偶校验位,c,bit-manipulation,bit,transmission,parity,C,Bit Manipulation,Bit,Transmission,Parity,我正在写一个程序,模拟通过网络传输字符。 我编写了以下函数: 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 <<bitNu
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 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
我似乎找不到我做错了什么,有人能帮我吗?您是否正在尝试为输入的每个字节设置奇偶校验位?您是否尝试设置偶数/奇数/或无奇偶校验?一个字节的最大值是255,那么(例如)3220从哪里来?它意味着什么?@user3629249 3220 3160 3264 3264 7420来自我的讲师提供的测试代码。我正试图设定一个均等点。我没有得到很多关于这段代码的说明。我得到的所有说明都是编解码器中的注释。您能提供更多关于此用法的信息吗?
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);
}